package com.edais.actions;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.edais.domain.*;
import com.edais.domain.gift.GiftPackage;
import com.edais.domain.gift.GiftSendDto;
import com.edais.log.IpLog;
import com.edais.service.*;
import com.edais.service.gift.GiftPackageOrderService;
import com.edais.service.gift.GiftPackageService;
import com.edais.util.*;
import com.edais.util.rsao2o.RSARequestO2O;
import com.edais.vo.PushData;
import com.lb.sssq.service.DepositService;
import com.yunzhi.domain.ResultCode;
import com.yunzhi.domain.ResultConstant;
import com.yunzhi.domain.ResultDTO;
import com.yunzhi.util.RequestUtil;
import com.yunzhi.util.ResponseUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/ldActivity")

public class WeixinLDActivityAction implements Serializable {
	private static final Log logger = LogFactory.getLog(WeixinLDActivityAction.class);

	@Autowired
	private UserService userService;

	@Autowired
	private ActivityService activityService;

	@Autowired
	private AssetsService assetsService;

	@Autowired
	private DepositService depositService;

	@Autowired
	private SMSService sMSService;

	@Autowired
	private FinancePlanOpfService financeService;

	@Autowired
	private WalletService walletService;

	@Autowired
	private LoanService loanService;

	@Autowired
	private OrderService orderService;

	@Autowired
	private KcodeChannelService kcodeChannelService;

	@Autowired
	private JkxyService jkxyService;

	@Autowired
	private ErrorMessageService errorMessageService;

	@Autowired
	private ChannelWelfareParametersService channelWelfareParametersService;

	@Autowired
	private PointService pointService;

	@Autowired
	private ShopVouchersService shopVouchersService;

	@Autowired
	private GiftPackageOrderService giftPackageOrderService;

	@Autowired
	private GiftPackageService giftPackageService;

	private String fmt = "yyyy-MM-dd HH:mm:ss";

	private static final String DECIFMT="#.00";
	/**
	 * 注册
	 * 
	 * @param request
	 * @param response
	 * @throws IllegalAccessException
	 * @throws IllegalArgumentException
	 */
	@RequestMapping(value = "/register")
	public void register(HttpServletRequest request, HttpServletResponse response) throws Exception {

		try {

			JSONObject params = RequestUtil.decodeDataJson(request);
			String mobileNumber = params.getString("mobileNumber");// 用户手机号
			String channel = params.getString("channel");// 渠道

			String ip = RequestUtil.getClientIP(request);

			IpLogBean logBean = new IpLogBean();
			logBean.setIp(ip);
			logBean.setAction("注册");
			logBean.setStatus(Consts.ERROR_CN);

			String setupFlag = "2";
			params.put("mobileNumber", mobileNumber);
			params.put("channel", channel);
			params.put("setupFlag", setupFlag);

			if ("2".equals(setupFlag)) {
				logBean.setDetail(mobileNumber + "在APP端进行了注册操作");
			} else {
				logBean.setDetail(mobileNumber + "在WEB端进行了注册操作");
			}

			ResultDTO checkResult = registerCheck(params);
			if (null == checkResult || checkResult.codeEq(ResultCode.FAILED)) {
				ResponseUtil.write(response,checkResult);
				return;
			}
			// 创建用户
			User user = new User();
			user.setMobile(mobileNumber);
			user.setChannel(channel);
			user.setLastest_login_ip(ip);
			String token = "register" + "_" + CommonUtil.getUuid();
			user.setLogin_token(token);
			user.setUtm_source_type(channel);
			Map<String, Object> resultMap = this.userService.coreLDAddUser(user, true);

			String rescode = resultMap.get("rescode").toString();

			if (rescode.equals(Consts.SUCCESS_CODE)) {

				String userId = resultMap.get("userId").toString();
				user.setId(Integer.parseInt(userId));

				this.userService.insertUserQuickWithdrawInfo(userId);
			}

			// 按渠道统一发放福利
			try {
				Map<String, Object> welfareParams = new HashMap<String, Object>();
				welfareParams.put("userId", user.getId());
				welfareParams.put("channelId", user.getUtm_source());
				welfareParams.put("mobile", user.getMobile());
				welfareParams.put("channelEnName", channel);
				channelWelfareParametersService.addWelfareBychannelEnName(welfareParams, request);
			} catch (Exception e) {
				logger.error("注册赠送福利异常:" + e.getMessage());
			}

			// 注册送积分
			if (null != user.getId() && !StringUtil.isEmpty(user.getMobile())) {
				logger.info("#### 开始执行--->注册送积分 #####");
				pointService.registerPoint(user);
				logger.info("#### 执行完成--->注册送积分 #####");
			} else {
				logger.info("#### 注册送积分时，用户信息有误，userId=" + user.getId() + ",mobile=" + user.getMobile() + " ####");
			}

			logBean.setStatus(Consts.SUCCESS_CN);
			if (StringUtils.isNotBlank(ip)) {
				logBean.setUser(user.getId() + "");
				IpLog.printIpLog(logBean);
			}
			ResponseUtil.write(response,ResultConstant.SUCCESS);
		} catch (Exception e) {
			logger.error("注册异常",e);
			ResponseUtil.write(response,ResultConstant.FAILED);
		}
	}

	/**
	 * 分享
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/shareNotify")
	public void shareNotify(HttpServletRequest request, HttpServletResponse response) {
		Map<String, String> paramsMap = new HashMap<String, String>();
		/*
		 * 1.判断用户是否使用过k码 2.判断用户是否分享或者好评过 3.理财产品生成
		 */
		// 解密请求参数
		String reqString = request.getQueryString();
		if (StringUtils.isBlank(reqString)) {
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "", "参数异常！");
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			return;
		}
		try {
			reqString = DES3Util.decode(reqString);
			reqString = java.net.URLDecoder.decode(reqString, "UTF-8");
			JSONObject jsonObj = JSONObject.parseObject(reqString);

			// 用户手机号
			String mobileNumber = jsonObj.getString("mobileNumber");
			// 渠道
			String channel = jsonObj.getString("channel");

			paramsMap.put("mobileNumber", mobileNumber);
			paramsMap.put("channel", channel);

			Map<String, String> checkMap = defCheck(paramsMap);
			if (null == checkMap || !Consts.SUCCESS_CODE.equals(checkMap.get("code"))) {
				String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), checkMap.get("code"), "",
						checkMap.get("message"));
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			}
			// 获取用户活动信息
			Map<String, String> kparamsMap = new HashMap<String, String>();
			kparamsMap.put("mobile", mobileNumber);
			Map<String, Object> userActivityInfoMap = this.userService.findUserActivityInfo(kparamsMap);

			// 判断是否使用过K码
			String activityKCodeFlg = userActivityInfoMap.get("activityKCodeFlg").toString();
			String activityShareFlg = userActivityInfoMap.get("activityShareFlg").toString();
			String activityPraiseFlg = userActivityInfoMap.get("activityPraiseFlg").toString();
			String result = "";
			if (activityKCodeFlg.equals("Y")) {
				if (activityShareFlg.equals("Y") || activityPraiseFlg.equals("Y")) {
					result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.CHECK_CODE, "",
							"您已经分享或好评，并领取过相应奖励！");
				} else {
					// 获取用户信息
					Map<String, Object> userMap = new HashMap<String, Object>();
					userMap.put("mobile", mobileNumber);
					User user = userService.getUserByParm(userMap);

					String spAmt = activityService.findParamValueByName("share_praise_exchange_amt");
					/**
					 * 生成理财主逻辑
					 */
					// 购买主业务
					Map<String, Object> pageMode = new HashMap<String, Object>();
					pageMode.put("mobile", mobileNumber);
					pageMode.put("channel", channel);

					pageMode.put("buyAmount", spAmt == null ? "0" : spAmt);
					pageMode.put("userId", user.getId());
					// 1:激活 2:分享 3:好评
					pageMode.put("stepStatus", "2");

					Map retMap = activityService.activityBidByBalance("分享送理财", pageMode);
					logger.debug("============赠送返回结果：" + retMap.toString());

					if (!Consts.SUCCESS_CODE.equals(retMap.get("rescode"))) {
						String message = (String) retMap.get("resmsg_cn");
						result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.CHECK_CODE,
								"生成理财产品失败！", message);
					} else {
						result = CommonUtil.setResultStringCn(retMap, Consts.SUCCESS_CODE, "", "分享送理财成功!");
					}
				}
			} else {
				result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "",
						"您还未激活过K码，不能进行分享!");
			}
			CommonUtil.responseJson(result, response);
		} catch (Exception e) {
			logger.error("分享回调异常:" + e.getMessage());
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "",
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		}
	}

	/**
	 * 好评上传
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/praise")
	public void praise(HttpServletRequest request, HttpServletResponse response) {
		Map<String, String> paramsMap = new HashMap<String, String>();
		// 解密请求参数
		String reqString = request.getQueryString();
		if (StringUtils.isBlank(reqString)) {
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "", "参数异常！");
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			return;
		}
		InputStream in = null;
		try {
			reqString = DES3Util.decode(reqString);
			reqString = java.net.URLDecoder.decode(reqString, "UTF-8");
			JSONObject jsonObj = JSONObject.parseObject(reqString);

			// 用户手机号
			String mobileNumber = jsonObj.getString("mobileNumber");
			// 渠道
			String channel = jsonObj.getString("channel");
			// 图片url
			String uploadImgUrl = jsonObj.getString("uploadImgUrl");

			paramsMap.put("mobileNumber", mobileNumber);
			paramsMap.put("channel", channel);
			paramsMap.put("uploadImgUrl", uploadImgUrl);

			try {
				// fastDFSUtil.upload(uploadImgUrl,
				// mobileNumber+"."+uploadImgUrl.split("[.]")[1]);
				File f = new File(uploadImgUrl);
				in = new FileInputStream(f);

				Map<String, Object> uploadMap = new HashMap<String, Object>();
				uploadMap.put("fileName",
						mobileNumber + "." + uploadImgUrl.substring(uploadImgUrl.lastIndexOf(".") + 1));
				uploadMap.put("inputStream", in);

				String restStr = this.activityService.modifyPic(uploadMap);
				if (StringUtils.isNotBlank(restStr)) {
					uploadImgUrl = restStr;
					f.delete();
				}
			} catch (Exception e) {
				logger.error(" 图片上传异常:" + e.getMessage());
			}

			Map<String, String> checkMap = defCheck(paramsMap);
			if (null == checkMap || !Consts.SUCCESS_CODE.equals(checkMap.get("code"))) {
				String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), checkMap.get("code"), "",
						checkMap.get("message"));
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			}
			// 获取用户活动信息
			Map<String, String> kparamsMap = new HashMap<String, String>();
			kparamsMap.put("mobile", mobileNumber);
			Map<String, Object> userActivityInfoMap = this.userService.findUserActivityInfo(kparamsMap);

			// 判断是否使用过K码
			String activityKCodeFlg = userActivityInfoMap.get("activityKCodeFlg").toString();
			String activityShareFlg = userActivityInfoMap.get("activityShareFlg").toString();
			String activityPraiseFlg = userActivityInfoMap.get("activityPraiseFlg").toString();
			String result = "";
			if (activityKCodeFlg.equals("Y")) {
				if (activityShareFlg.equals("Y") || activityPraiseFlg.equals("Y")) {
					result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "",
							"您已经分享或好评，并领取过相应奖励！");
				} else {
					// 获取用户信息
					Map<String, Object> userMap = new HashMap<String, Object>();
					userMap.put("mobile", mobileNumber);
					User user = userService.getUserByParm(userMap);

					String spAmt = activityService.findParamValueByName("share_praise_exchange_amt");

					/**
					 * 生成理财主逻辑
					 */
					// 购买主业务
					Map<String, Object> pageMode = new HashMap<String, Object>();
					pageMode.put("mobile", mobileNumber);
					pageMode.put("channel", channel);

					pageMode.put("buyAmount", spAmt == null ? "0" : spAmt);
					pageMode.put("uploadImgUrl", uploadImgUrl);
					pageMode.put("userId", user.getId());
					// 1:激活 2:分享 3:好评
					pageMode.put("stepStatus", "3");

					Map retMap = activityService.activityBidByBalance("好评上传", pageMode);
					logger.debug("============赠送返回结果：" + retMap.toString());

					if (!Consts.SUCCESS_CODE.equals(retMap.get("rescode"))) {
						String message = (String) retMap.get("resmsg_cn");
						result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.CHECK_CODE,
								"生成理财产品失败！", message);
					} else {
						result = CommonUtil.setResultStringCn(retMap, Consts.SUCCESS_CODE, "", "好评送理财成功！");
					}
				}
			} else {
				result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "",
						"您还未激活过K码，不能进行好评!");
			}
			CommonUtil.responseJson(result, response);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("好评异常:" + e.getMessage());
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "",
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 活动赠送理财取消
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/activityOrderCancel")
	public void activityOrderCancel(HttpServletRequest request, HttpServletResponse response) {
		String logInfo = "k码退货接口";
		// 解密请求参数
		String reqString = request.getQueryString();
		if (StringUtils.isBlank(reqString)) {
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "", "参数异常！");
			// 处理返回结果
			CommonUtil.responseJsonNotEncrypt(result, response);
			return;
		}

		try {
			// reqString = DES3Util.decode(reqString);
			reqString = java.net.URLDecoder.decode(reqString, "UTF-8");
			JSONObject jsonObj = JSONObject.parseObject(reqString);

			String channel = jsonObj.getString("channel"); // 平台识别码
			String idcardNo = jsonObj.getString("idcardNo"); // 卡号
			String operator = jsonObj.getString("operator"); // 操作人员

			Map<String, String> map = new HashMap<String, String>();
			map.put("idcardNo", idcardNo);
			map.put("channel", channel);
			map.put("operator", operator);
			
			logger.info(logInfo+" params {channel:"+channel+",idcardNo:"+idcardNo+",operator:"+operator+"}");
			
			Map<String, String> checkMap = this.orderCancelCheck(map);
			if (null == checkMap || !Consts.SUCCESS_CODE.equals(checkMap.get("code"))) {
				logger.error(logInfo+"code is null");
				String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), checkMap.get("code"), "",
						checkMap.get("message"));
				// 处理返回结果
				CommonUtil.responseJsonNotEncrypt(result, response);
				return;
			}
			
			// String channel = request.getParameter("channel"); //平台识别码
			// String idcardNo = request.getParameter("idcardNo"); //卡号
			// String operator = request.getParameter("operator"); //操作人员
			// 通过卡号查询订单
			Map<String, Object> paramsMap = new HashMap<String, Object>();
			paramsMap.put("card_no", idcardNo);
			String orderId = "";
			if (StringUtils.isBlank(idcardNo)) {
				logger.error(logInfo+"idcardNo is null");
				String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE,
						Consts.ErrorMsg.MSG00001, Message.CnDescriptionExpression.BUSINESSE_ERROR);

				// 处理返回结果
				CommonUtil.responseJsonNotEncrypt(result, response);
				logger.debug("ldActivity/activityOrderCancel 卡号为空！");
				return;
			}
			
			logInfo+=logInfo+" {idcardNo:"+idcardNo+"} ";
			// 查询活动信息
			List<UserLDActivityInfo> userLDActivityInfoList = this.activityService.findActivityInfoByParm(paramsMap);
			String result = "";
			if (userLDActivityInfoList != null && userLDActivityInfoList.size() > 0) {
				UserLDActivityInfo userLDActivityInfo = userLDActivityInfoList.get(0);
				if (userLDActivityInfo.getGift_package_order_id() != null) {
					logger.info(logInfo + "K码礼包取消");
					Map<String, Object> cancelMap = new HashMap<String, Object>();
					cancelMap.put("kcodeCardNo", idcardNo);
					Map<String, Object> cancelRetMap = giftPackageOrderService.cancelKcodeGiftPackage(logInfo,
							cancelMap);
					if (!"00000".equals(cancelRetMap.get("rescode"))) {
						logger.error(logInfo + "失败");
						String result2 = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE,
								"", (String)cancelRetMap.get("resmsg_cn"));
						CommonUtil.responseJsonNotEncrypt(result2, response);
						return;
					}
					
					// 更新活动状态为0
					UserLDActivityInfo activityInfo = new UserLDActivityInfo();
					activityInfo.setCard_no(idcardNo); // 卡号
					activityInfo.setIs_valid("0"); // 无效状态
					this.activityService.updateActivityInfoIsValid(activityInfo);
					
					Map<String, Object> retMap = giftPackageOrderService.queryGiftPackageOrderByCardNo(idcardNo, logInfo);
					retMap.put("updateNum",1);
					CommonUtil.responseJsonNotEncrypt(CommonUtil.setResultStringCn(retMap, Consts.SUCCESS_CODE, "", ""),
							response);
					return;
				}
				// 判断是否参考活动1
				if (StringUtils.isNotEmpty(userLDActivityInfo.getStep1_order_id())) {
					orderId = userLDActivityInfo.getStep1_order_id();
				}
				// 判断是否参考活动2
				if (StringUtils.isNotEmpty(userLDActivityInfo.getStep2_order_id())) {
					orderId += "," + userLDActivityInfo.getStep2_order_id();
				}
				if (StringUtils.isNotEmpty(orderId) && orderId.substring(0, 1).equals(",")) {
					orderId = orderId.substring(1, orderId.length());
				}
				paramsMap.put("orderState", 2);
				paramsMap.put("orderId", orderId);
				paramsMap.put("userId", operator);
				// 更新订单状态
				Map<String, Object> retMap = this.activityService.updateOrderStateByOrderId(paramsMap);
				if (!"00000".equals(retMap.get("rescode"))) {
					logger.error(logInfo + "更新订单状态失败！");
					String result2 = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "",
							Message.CnDescriptionExpression.BUSINESSE_ERROR);
					CommonUtil.responseJsonNotEncrypt(result2, response);
					return;
				}
				if ("0".equals(retMap.get("updateNum").toString())) {
					logger.error(logInfo + "更新订单状态失败！");
					String result2 = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "",
							Message.CnDescriptionExpression.BUSINESSE_PAYMENT_ERROR);
					// 处理返回结果
					CommonUtil.responseJsonNotEncrypt(result2, response);
					return;
				}

				Map<String, Object> kCodeParamsMap = new HashMap<String, Object>();
				kCodeParamsMap.put("card_no", idcardNo);
				Map<String, Object> retMap2 = this.activityService.queryReturnFinanceInfoByKCode(kCodeParamsMap);

				// 更新活动状态为0
				UserLDActivityInfo activityInfo = new UserLDActivityInfo();
				activityInfo.setCard_no(idcardNo); // 卡号
				activityInfo.setIs_valid("0"); // 无效状态
				this.activityService.updateActivityInfoIsValid(activityInfo);

				retMap.put("isActivation", retMap2.get("isActivation"));
				retMap.put("isExpire", retMap2.get("isExpire"));
				retMap.put("expireAmount", retMap2.get("expireAmount"));

				result = JsonUtil.getJsonStringFromMap(retMap);
			} else {
				logger.error(logInfo + "查询不到活动信息！");
				result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE,
						Consts.ErrorMsg.MSG00001, "查询不到活动信息");
			}
			// 处理返回结果
			CommonUtil.responseJsonNotEncrypt(result, response);
		} catch (Exception e) {
			logger.error(logInfo+ "退货异常", e);
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "",
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJsonNotEncrypt(result, response);
		}

	}

	/**
	 * 获取用户在该活动中信息
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/findUserActivityInfo")
	public void findUserActivityInfo(HttpServletRequest request, HttpServletResponse response) {
		Map<String, String> paramsMap = new HashMap<String, String>();

		// 解密请求参数
		String reqString = request.getQueryString();
		if (StringUtils.isBlank(reqString)) {
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "", "参数异常！");
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			return;
		}

		try {
			reqString = DES3Util.decode(reqString);
			reqString = java.net.URLDecoder.decode(reqString, "UTF-8");
			JSONObject jsonObj = JSONObject.parseObject(reqString);

			// 用户手机号
			String mobileNumber = jsonObj.getString("mobileNumber");
			// 渠道
			String channel = jsonObj.getString("channel");

			paramsMap.put("mobileNumber", mobileNumber);
			paramsMap.put("channel", channel);

			Map<String, String> checkMap = defCheck(paramsMap);
			if (null == checkMap || !Consts.SUCCESS_CODE.equals(checkMap.get("code"))) {
				String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), checkMap.get("code"), "",
						checkMap.get("message"));
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			}
			// 获取用户活动数据
			Map<String, String> kparamsMap = new HashMap<String, String>();
			kparamsMap.put("mobile", mobileNumber);

			Map<String, Object> retMap = this.userService.findUserActivityInfo(kparamsMap);

			String result = JsonUtil.getJsonStringFromMap(retMap);
			CommonUtil.responseJson(result, response);
		} catch (Exception e) {
			logger.error("获取用户在该活动中信息异常:" + e.getMessage());
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "",
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		}
	}

	/**
	 * 获取用户账户信息
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/findUserAcctInfo")
	public void findUserAcctInfo(HttpServletRequest request, HttpServletResponse response) {
		Map<String, String> paramsMap = new HashMap<String, String>();
		// 解密请求参数
		String reqString = request.getQueryString();
		if (StringUtils.isBlank(reqString)) {
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "", "参数异常！");
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			return;
		}
		Map<String, Object> rtnMap = new HashMap<String, Object>();
		rtnMap.put("acctBalance", "0");
		rtnMap.put("amountSum", "0");
		rtnMap.put("incomeSum", "0");
		rtnMap.put("investAmountSum", "0");
		rtnMap.put("currentAmount", "0");
		rtnMap.put("yesterdayIncome", "0");
		rtnMap.put("depositIncomeSum", "0");
		rtnMap.put("regularIncomeSum", "0");

		String result = "";
		try {
			reqString = DES3Util.decode(reqString);
			reqString = java.net.URLDecoder.decode(reqString, "UTF-8");
			JSONObject jsonObj = JSONObject.parseObject(reqString);

			// 用户手机号
			String mobileNumber = jsonObj.getString("mobileNumber");
			// 渠道
			String channel = jsonObj.getString("channel");

			paramsMap.put("mobileNumber", mobileNumber);
			paramsMap.put("channel", channel);

			Map<String, String> checkMap = defCheck(paramsMap);
			if (null == checkMap || !Consts.SUCCESS_CODE.equals(checkMap.get("code"))) {
				result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), checkMap.get("code"), "",
						checkMap.get("message"));
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			}
			// 获取用户ID
			Map<String, Object> userMap = new HashMap<String, Object>();
			userMap.put("mobile", mobileNumber);
			User user = userService.getUserByParm(userMap);

			// 获取我的资产总览
			String userId = String.valueOf(user.getId());
			paramsMap.put("userId", userId);
			String queryResult = activityService.queryMyAccountDetail(paramsMap);
			JSONObject queryResultObject = JSONObject.parseObject(queryResult);

			// 定期资产
			String investAmountSum = queryResultObject.getString("amountSum");
			rtnMap.put("investAmountSum", investAmountSum);

			Map<String, Object> assetsMap = this.assetsService.getAssets(userId);
			// 账户余额
			String balanceMoney = assetsMap.get("balanceMoney").toString();
			rtnMap.put("acctBalance", balanceMoney);
			// 账户总资产
			String totalAssets = assetsMap.get("totalAssets").toString();
			rtnMap.put("amountSum", totalAssets);
			// 账户累计收益
			String incomeAmount = assetsMap.get("incomeAmount").toString();
			rtnMap.put("incomeSum", incomeAmount);

			paramsMap.put("finaceId", "1");
			// app活期理财详情
			String fundDetailResult = depositService.queryMoneyFundDetail(paramsMap);
			JSONObject fundDetailObject = JSONObject.parseObject(fundDetailResult);
			// 昨日收益
			String yesterdayGain = fundDetailObject.getString("yesterdayGain");
			rtnMap.put("yesterdayIncome", yesterdayGain);
			// 活期累计收益
			String incomeTotal = fundDetailObject.getString("incomeTotal");
			rtnMap.put("depositIncomeSum", incomeTotal);
			// 定期累计收益
			BigDecimal regularIncomeSum = new BigDecimal(incomeAmount).subtract(new BigDecimal(incomeTotal));
			rtnMap.put("regularIncomeSum", regularIncomeSum);
			// 活期资产
			String accountAmount = fundDetailObject.getString("accountAmount");
			String currentIncome = fundDetailObject.getString("currentIncome");
			BigDecimal currentSum = new BigDecimal(accountAmount).add(new BigDecimal(currentIncome));
			rtnMap.put("currentAmount", currentSum);

			result = CommonUtil.setResultStringCn(rtnMap, Consts.SUCCESS_CODE, "", "");
		} catch (Exception e) {
			logger.debug("=====获取用户账户信息异常=====" + CommonUtil.printStackTraceToString(e));
			result = CommonUtil.setResultStringCn(rtnMap, Consts.ERROR_CODE, "",
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
		}
		CommonUtil.responseJson(result, response);
	}

	/**
	 * 激活K码
	 * 
	 * @param request
	 * @param response
	 * @throws IllegalAccessException
	 * @throws IllegalArgumentException
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "/activitiyKCodeUse")
	public void activitiyKCodeUse(HttpServletRequest request, HttpServletResponse response)
			throws IllegalArgumentException, IllegalAccessException {
		String logInfo = "kcodeActivate";
		String reqString = request.getQueryString();
		DecimalFormat deciformat = new DecimalFormat(DECIFMT);
		
		if (StringUtils.isBlank(reqString)) {
			Map<String, Object> errorMap = errorMessageService.getErrorMessage("EM000000007");
			String result = CommonUtil.setResultStringCn(errorMap, Consts.ERROR_CODE, "", getErrorMsg(errorMap));
			CommonUtil.responseJson(result, response);
			return;
		}
		try {
			
			reqString = DES3Util.decode(reqString);
			reqString = java.net.URLDecoder.decode(reqString, "UTF-8");
			
		} catch (Exception e) {
			logger.error(logInfo + "异常", e);
			Map<String, Object> errorMap = errorMessageService.getErrorMessage("EM000000007");
			String result = CommonUtil.setResultStringCn(errorMap, Consts.ERROR_CODE, "", getErrorMsg(errorMap));
			CommonUtil.responseJson(result, response);
		}
			
		HashMap<String, Object> reqMap = CommonUtil.jsonObjToHashMap(reqString);
		try {
			String mobileNumber = nullToBlank(reqMap.get("mobileNumber"));
			logInfo = logInfo + mobileNumber + "-";
			logger.info(logInfo + "开始");
			logger.info(logInfo + "激活参数：" + reqMap);
			String channel = nullToBlank(reqMap.get("channel"));
			String kCode = nullToBlank(reqMap.get("kCode"));
			String ip = nullToBlank(reqMap.get("ip"));
			
			if(StringUtils.isBlank(ip)){
				ip=CommonUtil.getClientIP(request);
				
			}
			/**
			 * 模式3 手机K码老年机 只有联通手机号才可以激活
			 * 验证K码激活上限，查询t_user_o2o_activity_info表中该用户有效的激活次数
			 * （is_valid=1的且MOBILE_KCODE_SIGN=1的数据的条数
			 * 与合作模式3的手机K码的可激活台数上限进行比较。大于等于上限则不可进行激活 该联通手机号只能激活一次
			 */
			String unionMobile = nullToBlank(reqMap.get("unionMobile"));

			// 激活k码参数检查
			Map<String, Object> checkMap = activateKcodeParamCheck(reqMap);
			if (checkMap == null || !Consts.SUCCESS_CODE.equals(checkMap.get("code"))) {
				String result = CommonUtil.setResultStringCn((Map) checkMap.get("errorMap"),
						(String) checkMap.get("code"), "", (String) checkMap.get("message"));
				CommonUtil.responseJson(result, response);
				return;
			}
			// 验证手机号是否注册
			Map<String, Object> userMap = new HashMap<String, Object>();
			userMap.put("mobile", mobileNumber);
			User user = userService.getUserByParm(userMap);
			if (user == null || user.getId() == null) {
				logger.info(logInfo + "手机号未注册");
				String result = CommonUtil.setResultStringCn(new HashMap(), Consts.ERROR_CODE, "", "手机号未注册");
				CommonUtil.responseJson(result, response);
				return;
			}
			String userId = String.valueOf(user.getId());

			// 验证尝试激活次数 t_user_activity_history_info
			Map<String, Object> pAttacksMap = kcodeChannelService.preventAttacks(logInfo, reqMap, userId);
			if (Consts.CHECK_CODE.equals(pAttacksMap.get("rescode"))) {
				logger.info(logInfo + "尝试激活次数过多");
				Map<String, Object> errorMap = (Map<String, Object>) pAttacksMap.get("errorMap");
				String result = CommonUtil.setResultStringCn(errorMap, Consts.CHECK_CODE, "", getErrorMsg(errorMap));
				CommonUtil.responseJson(result, response);
				return;
			}

			// 生成主账户
			Map<String, Object> relAcctMap = userService.findCusAcctInfo(userId);
			if ("0".equals(relAcctMap.get("count"))) {
				logger.info(logInfo + "生成主账户开始");
				this.userService.coreLDAddUser(user, false);
				logger.info(logInfo + "生成主账户结束");
			}

			// 激活k码系统 失败可能 网络异常，K码失效 lb_lingdang_kcode_use_url
			Map<String, Object> activityO2OMap = kcodeChannelService.activityO2OKcode(logInfo, reqMap);
			if (Consts.CHECK_CODE.equals(activityO2OMap.get("rescode"))) {
				logger.info(logInfo + "激活k码系统 失败");
				Map<String, Object> errorMap = (Map<String, Object>) activityO2OMap.get("errorMap");
				String result = CommonUtil.setResultStringCn(errorMap, Consts.CHECK_CODE, "", getErrorMsg(errorMap));
				CommonUtil.responseJson(result, response);
				return;
			}

			String cardNo = nullToBlank(activityO2OMap.get("cardNo"));
			BigDecimal bigKcAmt = new BigDecimal(nullToBlank(activityO2OMap.get("bigKcAmt")));
			logInfo+="-cardNo:"+cardNo;
			// 验证K码卡号是否非法
			Map<String, Object> illegalParmMap = new HashMap<String, Object>();
			illegalParmMap.put("cardNo", cardNo);
			if (kcodeChannelService.selectIllegal(illegalParmMap) > 0) {
				logger.info(logInfo + "K码卡号非法");
				Map<String, Object> errorMap = errorMessageService.getErrorMessage("EM000000026");
				String result = CommonUtil.setResultStringCn(errorMap, Consts.CHECK_CODE, "", getErrorMsg(errorMap));
				CommonUtil.responseJson(result, response);
				return;
			}
			// 验证K码卡号是否激活 t_user_o2o_activity_info
			Map<String, Object> cardNoMap = new HashMap<String, Object>();
			cardNoMap.put("card_no", cardNo);
			List<UserLDActivityInfo> activityInfoListRt = activityService.findActivityInfoByParm(cardNoMap);
			if (activityInfoListRt != null && activityInfoListRt.size() > 0) {
				logger.info(logInfo + cardNo + "卡号已激活");
				Map<String, Object> errorMap = errorMessageService.getErrorMessage("EM000000004");
				String result = CommonUtil.setResultStringCn(errorMap, Consts.CHECK_CODE, "", getErrorMsg(errorMap));
				CommonUtil.responseJson(result, response);
				return;
			}

			// K码渠道激活验证 t_keycode_channel
			Map<String, Object> kcodeQualifMap = kcodeChannelService.kcoadQualifCheck(logInfo, reqMap, cardNo, userId);
			if (Consts.CHECK_CODE.equals(kcodeQualifMap.get("rescode"))) {
				Map<String, Object> errorMap = (Map<String, Object>) kcodeQualifMap.get("errorMap");
				String result = CommonUtil.setResultStringCn(errorMap, Consts.CHECK_CODE, "", getErrorMsg(errorMap));
				CommonUtil.responseJson(result, response);
				return;
			}

			// k码和渠道信息
			Map<String, Object> channelMap = (Map<String, Object>) kcodeQualifMap.get("channelMap");
			Map<String, Object> retMap = new HashMap<String, Object>();

			// 判断是否走理财逻辑
			boolean isLicaiKcode=true;//默认走送理财
			
			String giftOnOff=activityService.findParamValueByName("gift_on-off");
			logger.info(logInfo + "-gift_on-off：" +giftOnOff );
			//若送礼包开关开，查询理财表，否则默认送理财
			if(giftOnOff.equalsIgnoreCase("Y")){
				isLicaiKcode = giftPackageOrderService.isGiftPackagetOrLiCai(cardNo, logInfo);
			}

			if (isLicaiKcode) {
				// 生成理财
				String jkxyType = ""; // 借款协议类型 1虚拟标 2真实标
				String lbAddAmount = "0";
				Map<String, Object> pageMode = new HashMap<String, Object>();
				pageMode.put("mobile", mobileNumber);
				pageMode.put("kCode", kCode);
				pageMode.put("channel", channel);
				pageMode.put("cardNo", cardNo);
				pageMode.put("stepStatus", "1");
				pageMode.put("buyAmount", bigKcAmt.toString());
				pageMode.put("userId", user.getId());
				pageMode.put("ip", ip);
				if (channelMap == null || channelMap.size() == 0 || ((BigDecimal)channelMap.get("ID")).longValue() == 1000) { // 无渠道
					logger.info(logInfo + "卡号不在渠道表中");
					/**
					 * 如果卡号在t_user_activity_keycode_list表中
					 * 送key_code_lb_exchange_amt元 activityLoan 如果 K码金额 =
					 * key_code_special_amt 且 卡号在 t_user_activity_keycode_ltmp 送
					 * key_code_use_for_days 天数的理财 否则送一月期理财
					 */
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("cardNo", cardNo);
					map.put("dataType", "0");
					List<UserActivityKeyCode> kcodeList = activityService.findKeyCodeListByParm(map);
					if (kcodeList != null && kcodeList.size() > 0) {
						lbAddAmount = activityService.findParamValueByName("key_code_lb_exchange_amt");
						if (StringUtils.isBlank(lbAddAmount)) {
							lbAddAmount = "0";
						}
						logger.info(logInfo + "卡号在t_user_activity_keycode_list表中，额外赠送" + lbAddAmount + "元");
					}
					pageMode.put("lbAddAmount", lbAddAmount);
					retMap = activityService.activityBidByBalance(logInfo, pageMode);
					logger.info(logInfo + "赠送理财成功");
				} else {
					logger.info(logInfo + "卡号在渠道表中");
					/**
					 * 支持合作模式 -1 0 1 2 3 4 5 6 activityLoanNew
					 */
					// 借款协议类型 1虚拟标 2真实标
					jkxyType = channelMap.get("JKXY_TYPE") + "";
					lbAddAmount = "0";
					if (StringUtils.isNotBlank(channelMap.get("ADDAMOUNT") + "")) {
						lbAddAmount = String.valueOf(channelMap.get("ADDAMOUNT"));
						logger.info(logInfo + "渠道额外赠送" + lbAddAmount + "元");
					}
					// 渠道K码额外赠送金额
					pageMode.put("lbAddAmount", channelMap.get("ADDAMOUNT"));
					pageMode.put("originalAmt", channelMap.get("AMOUNT")); // 渠道K码成本
					// 机构流水 记录K码金额及AMOUNT-K码金额的流水
					pageMode.put("logName1", channelMap.get("FX_MECHANISM"));
					// 网站流水 记录额外赠送金额
					pageMode.put("logName2", channelMap.get("MECHANISM"));
					pageMode.put("channerId", channelMap.get("ID"));
					pageMode.put("specialUserId", channelMap.get("SPECIAL_USER_ID")); // 经销商用户
					pageMode.put("specialUserName", channelMap.get("SPECIAL_USER_NAME"));
					pageMode.put("flag", channelMap.get("FLAG")); // 期数/天数
					pageMode.put("bidDay", channelMap.get("DAYS")); // 理财期数/天数
					pageMode.put("rate", channelMap.get("RATE")); // 理财利率
					// 额外赠送代金券 数量1 代金券规则ID
					pageMode.put("vouchersType", channelMap.get("VOUCHERS_TYPE"));
					pageMode.put("coopmodel", channelMap.get("COOP_MODEL"));
					// 联通手机号 合作模式3专用，用于区分同一联通手机号激活次数
					pageMode.put("unionMobile", unionMobile);
					// 赠送理财及加息券
					retMap = kcodeChannelService.activityBidByBalanceNew(logInfo, pageMode);
				}
				if (!Consts.SUCCESS_CODE.equals(retMap.get("rescode"))) {
					Map<String, Object> errorMap = errorMessageService.getErrorMessage("EM000000007");
					String result = CommonUtil.setResultStringCn(errorMap, Consts.CHECK_CODE, "",
							getErrorMsg(errorMap));
					CommonUtil.responseJson(result, response);
					return;
				}

				logger.info(logInfo + "异步生成借款协议开始");
				Map<String, String> paraMap = new HashMap<String, String>();
				paraMap.put("orderId", retMap.get("orderId") == null ? "" : (String) retMap.get("orderId"));
				paraMap.put("jkxyType", jkxyType);
				jkxyService.setJkxyForK("loanAgreement", paraMap);
				logger.info(logInfo + "异步生成借款协议结束");
				logger.info(logInfo + "发送短信开始");
				try {
					// 尊敬的{2}用户，您已成功激活K码并获得人民币{0}元的{1}理财产品。请登录联币金融平台查看。
					sMSService.getSMS(user.getId() + "", "sms08001",
							deciformat.format(bigKcAmt.add(new BigDecimal(lbAddAmount))), (String) retMap.get("cpType"));
				} catch (Exception e) {
					logger.error(logInfo + "发送短信异常", e);
				}
				retMap.put("type", "licai");
				logger.info(logInfo + "发送短信结束");
			} else {
				// 赠送K码礼包
				GiftSendDto giftSendDto = new GiftSendDto();
				giftSendDto.setUserId(user.getId().longValue());
				giftSendDto.setUserMobile(user.getMobile());
				giftSendDto.setUserName(user.getNick_name());
				GiftPackage kcodeGiftPackage = giftPackageService
						.selectByPrimaryKey(((BigDecimal) channelMap.get("GIFT_KCODE_PACKAGE")).longValue());
				giftSendDto.setPackageId(kcodeGiftPackage.getId());
				giftSendDto.setPackageName(kcodeGiftPackage.getName());
				giftSendDto.setPackageType(kcodeGiftPackage.getType());
				giftSendDto.setPackageTypeName(kcodeGiftPackage.getTypeName());
				giftSendDto.setPackageContent(kcodeGiftPackage.getContent());
				giftSendDto.setPackageExchangeServiceName(kcodeGiftPackage.getExchangeServiceName());
				giftSendDto.setPackageExchangeServiceParam(kcodeGiftPackage.getExchangeServiceParam());

				giftSendDto.setKcode(kCode);
				giftSendDto.setKcodeCardno(cardNo);
				giftSendDto.setKcodeType(channelMap.get("K_TYPE").toString());

				giftSendDto.setKcodeOriMoney(bigKcAmt);
				if ("1".equals(channelMap.get("FLAG"))) { // 0天数 1期数
					giftSendDto.setKcodeDays(Integer.valueOf(channelMap.get("DAYS").toString()) * 30);
				} else {
					giftSendDto.setKcodeDays(Integer.valueOf(channelMap.get("DAYS").toString()));
				}
				giftSendDto.setKcodeChannelId(((BigDecimal) channelMap.get("ID")).longValue());
				giftSendDto.setKcodeChannelName((String) channelMap.get("BUY_CHANNEL"));
				if(channelMap.get("SPECIAL_USER_ID") != null){
					giftSendDto.setKcodeChannelUserId(((BigDecimal) channelMap.get("SPECIAL_USER_ID")).longValue());
				}
				giftSendDto.setKcodeChannelMoney((BigDecimal) channelMap.get("AMOUNT"));

				giftSendDto.setKcodeLbAddMoney((BigDecimal) channelMap.get("ADDAMOUNT"));
				giftSendDto.setKcodeLbAgencyName((String) channelMap.get("LB_AGENCY_NAME"));
				giftSendDto.setActivityPlatform(channel);

				if (giftSendDto.getKcodeLbAddMoney() != null) {
					logger.info(logInfo + "礼包_渠道额外赠送" + giftSendDto.getKcodeLbAddMoney() + "元");
				}
				retMap = activityService.kcodeGiftSend(logInfo, BeanUtil.getMapFromBean(giftSendDto));
				if (!Consts.SUCCESS_CODE.equals(retMap.get("rescode"))) {
					Map<String, Object> errorMap = errorMessageService.getErrorMessage("EM000000007");
					String result = CommonUtil.setResultStringCn(errorMap, Consts.CHECK_CODE, "",
							getErrorMsg(errorMap));
					CommonUtil.responseJson(result, response);
					return;
				}
				// 异步赠送福利礼包
				if (channelMap.containsKey("GIFT_WELFARE_PACKAGE") && channelMap.get("GIFT_WELFARE_PACKAGE") != null) {
					Map<String, String> welfareMap = new HashMap<String, String>();
					welfareMap.put("userId", userId);
					welfareMap.put("mobile", mobileNumber);
					welfareMap.put("packageId", channelMap.get("GIFT_WELFARE_PACKAGE").toString());
					giftPackageService.giveWelFarePackage(welfareMap);
				}
				// 发送短信
				// 尊敬的{0}用户，您已成功激活K码并获得价值人民币{1}元的K码礼包。请登录联币金融平台查看。
				sMSService.sendSMS(logInfo, mobileNumber, "sms08002",
						userService.getUserInfo(userId).getReal_name(),
						deciformat.format(bigKcAmt.add(giftSendDto.getKcodeLbAddMoney() == null ? BigDecimal.ZERO
								: giftSendDto.getKcodeLbAddMoney())));
				retMap.put("type", "libao");
			}
			// GPS信息
			String latitude = nullToBlank(reqMap.get("latitude"));
			String longitude = nullToBlank(reqMap.get("longitude"));
			String gpsProvince = nullToBlank(reqMap.get("gpsProvince"));
			String gpsCity = nullToBlank(reqMap.get("gpsCity"));
			String gpsAddress = nullToBlank(reqMap.get("gpsAddress"));
			String gps = "";
			if (!"".equals(latitude) && !"".equals(longitude)) {
				gps = longitude + "," + latitude;
			}
			Map<String, Object> areaInfoMap = new HashMap<String, Object>();
			areaInfoMap.put("ip", ip);
			areaInfoMap.put("mobile", mobileNumber);
			areaInfoMap.put("cardNo", cardNo);
			if (!"".equals(gps)) {
				areaInfoMap.put("gps", gps);
			}
			// 如果取到GPS信息，存数据库，否则调用同盾接口获取IP归属地
			if (!"".equals(gps) && !"".equals(gpsAddress)) {
				logger.info(logInfo + "取到GPS信息");
				areaInfoMap.put("gpsProvince", gpsProvince);
				areaInfoMap.put("gpsCity", gpsCity);
				areaInfoMap.put("gpsAddress", gpsAddress);
				kcodeChannelService.setGpsInfo(areaInfoMap);
			} else {
				logger.info(logInfo + "未取到GPS信息，将异步调用同盾接口");
				String token_id = nullToBlank(reqMap.get("token_id")); // 同盾token_id
				logger.info(logInfo + "取到同盾token_id");
				areaInfoMap.put("token_id", token_id);
				kcodeChannelService.setAreaInfoByTd(areaInfoMap);
			}
			// 送一元券
			logger.info(logInfo + "送一元券开始");
			try {
				Map<String, Object> vsMap = new HashMap<String, Object>();
				vsMap.put("userId", userId);
				vsMap.put("mobile", mobileNumber);
				vsMap.put("voucherId", 1);
				vsMap.put("source", "1");
				shopVouchersService.addShopVouchers(vsMap);
			} catch (Exception e) {
				logger.info(logInfo + "送一元券异常", e);
			}
			logger.info(logInfo + "送一元券结束");
			// 送积分
			this.pointService.kcodePoint(logInfo, user, cardNo);
			
			// 新增 k码激活成功后更新版本提示信息(只礼包走)
			if(!isLicaiKcode){
				if(isOldVersion(logInfo,reqMap)){
					Map<String, Object> errorMap = errorMessageService.getErrorMessage("EM000000030");
					String result = CommonUtil.setResultStringCn(errorMap, Consts.CHECK_CODE, "",
							getErrorMsg(errorMap));
					
					logger.info(logInfo + "结束");
					
					CommonUtil.responseJson(result, response);
					return;
				}else{
					logger.info(logInfo+"当前版本大于3.2.0");
				}
			}
			logger.info(logInfo + "结束");
			// 激活成功
			CommonUtil.responseJson(CommonUtil.setResultStringCn(retMap, Consts.SUCCESS_CODE, "", ""), response);
		} catch (Exception e) {
			logger.error(logInfo + "异常", e);
			Map<String, Object> errorMap = errorMessageService.getErrorMessage("EM000000007");
			String result = CommonUtil.setResultStringCn(errorMap, Consts.ERROR_CODE, "", getErrorMsg(errorMap));
			CommonUtil.responseJson(result, response);
			return;
		}
	}

	
	/**
	 * 
	 * @Description: 获取错误信息
	 * @param @param
	 *            errorMap
	 * @param @return
	 * @return String
	 * @throws @author
	 *             wuhan
	 * @date 2016-7-13
	 */
	private String getErrorMsg(Map<String, Object> errorMap) {
		// TODO Auto-generated method stub
		ErrorMessageSetting emsEntity = (ErrorMessageSetting) errorMap.get("errorMessage");
		String emsStr = "";
		if (null != emsEntity) {
			emsStr = emsEntity.getMessage_content();
		}
		return emsStr;
	}

	/**
	 * 
	 * @Description: 通过卡号查询k码和渠道信息
	 * @param @param
	 *            cardNo
	 * @param @return
	 * @param @throws
	 *            Exception
	 * @return Map<String,Object>
	 * @throws @author
	 *             wuhan
	 * @date 2016-7-13
	 */
	private Map<String, Object> queryChannelList(Map<String, Object> parmMap) throws Exception {
		// Map<String,Object> parmMap=new HashMap<String,Object>();
		// parmMap.put("cardNo", cardNo);
		// parmMap.put("keyCode", keyCode);
		return kcodeChannelService.selectCardNo(parmMap);
	}

	/**
	 * 获取K码激活资格数据
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/findUseCompetency")
	public void findUseCompetency(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		// 解密请求参数
		String reqString = request.getQueryString();
		if (StringUtils.isBlank(reqString)) {
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "", "参数异常！");
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			return;
		}
		try {
			reqString = DES3Util.decode(reqString);
			reqString = java.net.URLDecoder.decode(reqString, "UTF-8");
			HashMap<String, Object> reqMap = CommonUtil.jsonObjToHashMap(reqString);

			// 用户手机号
			String mobileNumber = nullToBlank(reqMap.get("mobileNumber"));
			// 校验手机号不能为空
			if (StringUtils.isBlank(mobileNumber)) {
				logger.error("数据检查失败： 用户名为空");
				String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.CHECK_CODE, "",
						Message.CnDescriptionExpression.USER_IS_NULL);
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			}

			// 非法手机号检查
			boolean flag = mobileNumber.matches(Consts.PHONECHECK);
			if (!flag) {
				logger.error("数据检查失败：  手机号格式不对");
				String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.CHECK_CODE, "",
						Message.CnDescriptionExpression.MOBILE_IS_NON_STANDARD);
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			}
			// 获取用户信息
			Map<String, Object> userMap = new HashMap<String, Object>();
			userMap.put("mobile", mobileNumber);
			User user = userService.getUserByParm(userMap);

			Map<String, Object> k1Parm = new HashMap<String, Object>();
			k1Parm.put("mobile", mobileNumber);
			k1Parm.put("userId", user.getId());

			Map<String, Object> competencyMap = kcodeChannelService.kCodeUseCompetency(k1Parm);
			resultMap.put("isUseFlg", competencyMap.get("isUseFlg"));
			resultMap.put("useFlg", competencyMap.get("useFlg"));
			resultMap.put("isToplimit", competencyMap.get("isToplimit"));
			resultMap.put("nowUseNum", competencyMap.get("nowUseNum"));
			resultMap.put("canUseNum", competencyMap.get("canUseNum"));
			resultMap.put("totalToplimitNum", competencyMap.get("totalToplimitNum"));
			resultMap.put("needAmount", competencyMap.get("needAmount"));
			resultMap.put("remanPeriods", competencyMap.get("remanPeriods"));
			resultMap.put("resmsg_cn", competencyMap.get("resmsg_cn"));

			String result = CommonUtil.setResultStringCn(resultMap, Consts.SUCCESS_CODE, "", "");
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		} catch (Exception e) {
			logger.error("获取资格数据 异常:" + CommonUtil.printStackTraceToString(e));
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "",
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		}
	}

	/**
	 * 查询理财信息及k码激活状态（斐讯接口）
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/queryReturnFinanceInfo")
	public void queryReturnFinanceInfo(HttpServletRequest request, HttpServletResponse response) {
		Map<String, String> paramsMap = new HashMap<String, String>();
		// 解密请求参数
		String reqString = request.getQueryString();
		if (StringUtils.isBlank(reqString)) {
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "", "参数异常！");
			// 处理返回结果
			CommonUtil.responseJsonNotEncrypt(result, response);
			return;
		}
		String result = "";
		try {
			// reqString = DES3Util.decode(reqString);
			reqString = java.net.URLDecoder.decode(reqString, "UTF-8");
			JSONObject jsonObj = JSONObject.parseObject(reqString);

			// 卡号
			String idcardNo = jsonObj.getString("idcardNo");
			// 操作员
			String operator = jsonObj.getString("operator");
			// 渠道
			String channel = jsonObj.getString("channel");

			paramsMap.put("channel", channel);
			paramsMap.put("operator", operator);
			paramsMap.put("idcardNo", idcardNo);

			Map<String, String> checkMap = queryReturnFinanceInfoCheck(paramsMap);
			if (null == checkMap || !Consts.SUCCESS_CODE.equals(checkMap.get("code"))) {
				result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), checkMap.get("code"), "",
						checkMap.get("message"));
				// 处理返回结果
				CommonUtil.responseJsonNotEncrypt(result, response);
				return;
			}

			// 判断走理财还是走礼包
			String logInfo = "查询K码激活状态信息CardNo：" + idcardNo;
			
			Map<String, Object> kCodeParamsMap = new HashMap<String, Object>();
			kCodeParamsMap.put("card_no", idcardNo);
			List<UserLDActivityInfo> activityInfoList = activityService.findActivityInfoByParm(kCodeParamsMap);
			if (activityInfoList != null && activityInfoList.size() > 0) {
				UserLDActivityInfo activityInfo = activityInfoList.get(0);
				// 判断走理财还是走礼包
				if (activityInfo.getGift_package_order_id() != null) {
					logger.info(logInfo + "走礼包");
					Map<String, Object> retMap = giftPackageOrderService.queryGiftPackageOrderByCardNo(idcardNo, logInfo);
					// 处理返回结果
					result = CommonUtil.setResultStringCn(retMap, Consts.SUCCESS_CODE, "", "");
					logger.info(logInfo + "调用业务方法返回结果result=" + result);
					CommonUtil.responseJsonNotEncrypt(result, response);
					return;
				}
			}

			logger.info(logInfo + "走理财");
			Map<String, Object> retMap = this.activityService.queryReturnFinanceInfoByKCode(kCodeParamsMap);
			// 处理返回结果
			result = CommonUtil.setResultStringCn(retMap, Consts.SUCCESS_CODE, "", "");
			CommonUtil.responseJsonNotEncrypt(result, response);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("查询理财信息及k码激活状态异常:" + e.getMessage());
			result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "",
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJsonNotEncrypt(result, response);
		}
	}

	/**
	 * 冻结理财（斐讯接口）
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/activityFrozen")
	public void activityFrozen(HttpServletRequest request, HttpServletResponse response) {
		
		String logInfo = "冻结理财接口 " ;
		logger.info(logInfo+"开始；");
		// 解密请求参数
		String reqString = request.getQueryString();
		if (StringUtils.isBlank(reqString)) {
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "", "参数异常！");
			// 处理返回结果
			CommonUtil.responseJsonNotEncrypt(result, response);
			return;
		}
		String result = "";
		try {
			reqString = java.net.URLDecoder.decode(reqString, "UTF-8");
			HashMap<String, Object> reqMap = CommonUtil.jsonObjToHashMap(reqString);

			String channel = reqMap.get("channel") == null ? "" : reqMap.get("channel").toString();
			String idcardNo = reqMap.get("idcardNo") == null ? "" : reqMap.get("idcardNo").toString();
			String autoFlg = reqMap.get("autoFlg") == null ? "" : reqMap.get("autoFlg").toString();
			
			logger.info(logInfo+" params {channel:"+channel+",idcardNo:"+idcardNo+",autoFlg:"+autoFlg+"}");
			
			// channel
			if (StringUtils.isBlank(channel) || !"PHICOMM".equals(channel)) {
				logger.error(logInfo+"，数据检查失败  {channel:" + channel+"}");
				result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "", "渠道参数不正确!");
				// 处理返回结果
				CommonUtil.responseJsonNotEncrypt(result, response);
				return;
			}

			if (StringUtils.isBlank(idcardNo)) {
				logger.error(logInfo+"，数据检查失败 {idcardNo:" + idcardNo+"}");
				result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "", "卡号参数不正确!");
				// 处理返回结果
				CommonUtil.responseJsonNotEncrypt(result, response);
				return;
			}

			logInfo+="，{idcardNo:"+idcardNo+"} ";
			
			// 给自动处理放开时间限制
			if (!"Y".equals(autoFlg)) {
				// 操作时间判定
				SimpleDateFormat ymdhmsFormat = new SimpleDateFormat("yyyyMMddHHmmss");
				SimpleDateFormat hmsFormat = new SimpleDateFormat("HH:mm");
				Date now = new Date();
				Calendar cal = Calendar.getInstance();
				cal.setTime(now);
				int nowHours = cal.get(Calendar.HOUR_OF_DAY);
				// 获取起始时间边界
				String afterTimeStr = activityService.findParamValueByName("frozen_order_after_time");
				Date afterTime = ymdhmsFormat.parse(ymdhmsFormat.format(now).substring(0, 8) + afterTimeStr);
				// 判定跨天
				// 获取结束时间边界 如果跨天且在结束范围内则起始时间日期减1
				String housNum = activityService.findParamValueByName("frozen_order_hous_num");
				cal.setTime(afterTime);
				int afterHours = cal.get(Calendar.HOUR_OF_DAY);
				int endHours = afterHours + Integer.parseInt(housNum);
				if (endHours >= 24 && endHours - 24 >= nowHours) {
					cal.add(Calendar.DATE, -1);
					afterTime = cal.getTime();
				}
				cal.setTime(afterTime);
				cal.add(Calendar.HOUR_OF_DAY, Integer.parseInt(housNum));
				Date endTime = cal.getTime();

				if (now.getTime() > afterTime.getTime() && now.getTime() < endTime.getTime()) {
					logger.error(logInfo+"系统时间(" + hmsFormat.format(afterTime) + "~" + hmsFormat.format(cal.getTime()) + ")不能进行冻结操作!");
					result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "",
							"系统时间" + hmsFormat.format(afterTime) + "~" + hmsFormat.format(cal.getTime()) + "不能进行冻结操作!");
					// 处理返回结果
					CommonUtil.responseJsonNotEncrypt(result, response);
					return;
				}
			}

			// 根据卡号获取订单信息
			Map<String, Object> parmMap = new HashMap<String, Object>();
			parmMap.put("card_no", idcardNo);
			parmMap.put("channel", channel);
			List<UserLDActivityInfo> activityInfoList = activityService.findActivityInfoByParm(parmMap);
			// 有数据说明已被激活
			logger.info(logInfo + " k码理财冻结开始");
			
			if (activityInfoList != null && activityInfoList.size() > 0) {
				UserLDActivityInfo activityInfo = activityInfoList.get(0);

				// 判断走理财还是走礼包
				if (activityInfo.getGift_package_order_id() != null) {
					logger.info(logInfo + "，{Phone:" + activityInfo.getMobile() + "} 【k码礼包理财冻结 开始】");
					Map<String, Object> jsonMap = giftPackageOrderService.giftPackageFrozen(idcardNo, logInfo+"{Phone:" + activityInfo.getMobile() + "}", 2);
					result = JsonUtil.getJsonStringFromMap(jsonMap);
					CommonUtil.responseJsonNotEncrypt(result, response);
					return;
				}

				

				Map<String, Object> userMap = new HashMap<String, Object>();
				userMap.put("mobile", activityInfo.getMobile());
				User user = userService.getUserByParm(userMap);
				String userId = String.valueOf(user.getId());

				String orderId = activityInfo.getStep1_order_id();
				parmMap.put("orderId", orderId);
				parmMap.put("frozenStatus", "1");
				parmMap.put("userId", userId);
				
				logger.info(logInfo + "k码理财冻结"+" params {mobile:"+activityInfo.getMobile()+",orderId:"+orderId+",userId:"+userId+"}");
				
				Map<String, Object> retMap = activityService.frozenOrderByOrderId(parmMap);
				// 处理返回结果
				result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), retMap.get("rescode").toString(),
						"", retMap.get("resmsg_cn").toString());
				logger.info(logInfo + "k码理财冻结结束");
				CommonUtil.responseJsonNotEncrypt(result, response);
			} else {
				Map<String, Object> forMap = activityService.upFrozenByCardNo(parmMap);

				result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), forMap.get("rescode").toString(),
						"", forMap.get("resmsg_cn").toString());
				
				logger.info(logInfo + "k码理财冻结结束");
				// 处理返回结果
				CommonUtil.responseJsonNotEncrypt(result, response);
				return;
			}
		} catch (Exception e) {
			logger.error(logInfo+" 查询理财信息及k码激活状态异常:" + CommonUtil.printStackTraceToString(e));
			result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "",
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
			logger.info(logInfo + "k码理财冻结结束");
			// 处理返回结果
			CommonUtil.responseJsonNotEncrypt(result, response);
		}
	}

	/**
	 * 解冻理财（斐讯接口）
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/activityFrozenCancel")
	public void activityFrozenCancel(HttpServletRequest request, HttpServletResponse response) {
		String logInfo="解冻理财接口  ";
		logger.info(logInfo + "开始");
		Map<String, String> paramsMap = new HashMap<String, String>();
		// 解密请求参数
		String reqString = request.getQueryString();
		if (StringUtils.isBlank(reqString)) {
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "", "参数异常！");
			// 处理返回结果
			CommonUtil.responseJsonNotEncrypt(result, response);
			return;
		}
		
		String result = "";
		try {
			reqString = java.net.URLDecoder.decode(reqString, "UTF-8");
			HashMap<String, Object> reqMap = CommonUtil.jsonObjToHashMap(reqString);

			String channel = reqMap.get("channel") == null ? "" : reqMap.get("channel").toString();
			String idcardNo = reqMap.get("idcardNo") == null ? "" : reqMap.get("idcardNo").toString();
			logger.info(logInfo + "params:{channel:"+channel+",idcardNo:"+idcardNo+"}");
			logInfo+=logInfo+"{idcardNo:"+idcardNo+"}";
			// channel
			if (StringUtils.isBlank(channel) || !"PHICOMM".equals(channel)) {
				logger.error(logInfo+"数据检查失败：{channel:" + channel+"}");
				result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "", "渠道参数不正确!");
				// 处理返回结果
				CommonUtil.responseJsonNotEncrypt(result, response);
				return;
			}

			if (StringUtils.isBlank(idcardNo)) {
				logger.error(logInfo+"数据检查失败：{idcardNo:" + idcardNo+"}");
				result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "", "卡号参数不正确!");
				// 处理返回结果
				CommonUtil.responseJsonNotEncrypt(result, response);
				return;
			}

			// 操作时间判定
			SimpleDateFormat ymdhmsFormat = new SimpleDateFormat("yyyyMMddHHmmss");
			SimpleDateFormat hmsFormat = new SimpleDateFormat("HH:mm");
			Date now = new Date();
			Calendar cal = Calendar.getInstance();
			cal.setTime(now);
			int nowHours = cal.get(Calendar.HOUR_OF_DAY);
			// 获取起始时间边界
			String afterTimeStr = activityService.findParamValueByName("frozen_order_after_time");
			Date afterTime = ymdhmsFormat.parse(ymdhmsFormat.format(now).substring(0, 8) + afterTimeStr);
			// 判定跨天
			// 获取结束时间边界 如果跨天且在结束范围内则起始时间日期减1
			String housNum = activityService.findParamValueByName("frozen_order_hous_num");
			cal.setTime(afterTime);
			int afterHours = cal.get(Calendar.HOUR_OF_DAY);
			int endHours = afterHours + Integer.parseInt(housNum);
			if (endHours >= 24 && endHours - 24 >= nowHours) {
				cal.add(Calendar.DATE, -1);
				afterTime = cal.getTime();
			}
			cal.setTime(afterTime);
			cal.add(Calendar.HOUR_OF_DAY, Integer.parseInt(housNum));
			Date endTime = cal.getTime();

			if (now.getTime() > afterTime.getTime() && now.getTime() < endTime.getTime()) {
				logger.error(logInfo+"系统时间(" + hmsFormat.format(afterTime) + "~" + hmsFormat.format(cal.getTime()) + ")不能进行解冻操作!");
				result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "",
						"系统时间" + hmsFormat.format(afterTime) + "~" + hmsFormat.format(cal.getTime()) + "不能进行解冻操作!");
				// 处理返回结果
				CommonUtil.responseJsonNotEncrypt(result, response);
				return;
			}

			// 根据卡号获取订单信息
			Map<String, Object> parmMap = new HashMap<String, Object>();
			parmMap.put("card_no", idcardNo);
			List<UserLDActivityInfo> activityInfoList = activityService.findActivityInfoByParm(parmMap);
			if (activityInfoList != null && activityInfoList.size() > 0) {
				UserLDActivityInfo activityInfo = activityInfoList.get(0);

				// 判断走理财还是走礼包
				if (activityInfo.getGift_package_order_id() != null) {
					logger.info(logInfo + "{phone:"+activityInfo.getMobile()+"}解冻理财走礼包");
					Map<String, Object> jsonMap = giftPackageOrderService.giftPackageFrozen(idcardNo, logInfo+"{phone:"+activityInfo.getMobile()+"}", 1);
					result = JsonUtil.getJsonStringFromMap(jsonMap);
					CommonUtil.responseJsonNotEncrypt(result, response);
					return;
				}

				logger.info(logInfo + "解冻理财走理财");

				Map<String, Object> userMap = new HashMap<String, Object>();
				userMap.put("mobile", activityInfo.getMobile());
				User user = userService.getUserByParm(userMap);
				String userId = String.valueOf(user.getId());

				String orderId = activityInfo.getStep1_order_id();
				parmMap.put("orderId", orderId);
				parmMap.put("frozenStatus", "0");
				parmMap.put("userId", userId);

				Map<String, Object> retMap = activityService.frozenOrderByOrderId(parmMap);
				// 处理返回结果
				result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), retMap.get("rescode").toString(),
						"", retMap.get("resmsg_cn").toString());
				CommonUtil.responseJsonNotEncrypt(result, response);
			} else {
				Map<String, Object> forMap = activityService.upFrozenCancelByCardNo(parmMap);

				result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), forMap.get("rescode").toString(),
						"", forMap.get("resmsg_cn").toString());
				// 处理返回结果
				CommonUtil.responseJsonNotEncrypt(result, response);
				return;
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(logInfo+"查询理财信息及k码激活状态异常:" + CommonUtil.printStackTraceToString(e));
			result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "",
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJsonNotEncrypt(result, response);
		}
	}

	/**
	 * 短信发送电子K码接口
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/sendKeyCode")
	public void sendKeyCode(HttpServletRequest request, HttpServletResponse response) {
		Map<String, String> paramsMap = new HashMap<String, String>();
		String logInfo  = "sendKeyCode";
		// 解密请求参数
		String reqString = request.getQueryString();
		if (StringUtils.isBlank(reqString)) {
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "", "参数异常！");
			// 处理返回结果
			CommonUtil.responseJsonNotEncrypt(result, response);
			return;
		}
		String result = "";
		try {
			// reqString = DES3Util.decode(reqString);
			reqString = java.net.URLDecoder.decode(reqString, "UTF-8");
			JSONObject jsonObj = JSONObject.parseObject(reqString);

			// 短息内容
			String message = jsonObj.getString("message");
			// 手机号
			String mobileNumber = jsonObj.getString("mobileNumber");
			// 渠道
			/*String channel = jsonObj.getString("channel");

			paramsMap.put("channel", channel);
			paramsMap.put("message", "【糯糯金融】" + message + " 详情请查看天猫斐讯店铺相应活动介绍或拨打客服热线4006-999-211");
			paramsMap.put("mobileNumber", mobileNumber);*/

			Map<String, String> checkMap = defCheck(paramsMap);
			if (null == checkMap || !Consts.SUCCESS_CODE.equals(checkMap.get("code"))) {
				result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), checkMap.get("code"), "",
						checkMap.get("message"));
				// 处理返回结果
				CommonUtil.responseJsonNotEncrypt(result, response);
				return;
			}

			//Map<String, Object> retMap = activityService.sendKeyCode(paramsMap);
			Map<String, Object> retMap = sMSService.sendSMS(logInfo, mobileNumber, "sms10001", message);
			
			// 处理返回结果
			result = CommonUtil.setResultStringCn(retMap, Consts.SUCCESS_CODE, "", "");
			CommonUtil.responseJsonNotEncrypt(result, response);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("短信发送电子K码异常:" + e.getMessage());
			result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, e.getMessage(),
					e.getMessage());
			// 处理返回结果
			CommonUtil.responseJsonNotEncrypt(result, response);
		}

	}

	/**
	 * 数据检查
	 * 
	 * @param paramsMap
	 * @return
	 * @throws Exception
	 */
	private Map<String, String> defCheck(Map<String, String> paramsMap) throws Exception {
		Map<String, String> resMap = new HashMap<String, String>();
		String mobileNumber = paramsMap.get("mobileNumber");// 用户手机号
		String channel = paramsMap.get("channel"); // 渠道
		// 渠道集合
		List<String> channelList = new ArrayList<String>();
		channelList.add("PHICOMM");
		channelList.add("WEBSITE");
		channelList.add("LINGDANG");
		channelList.add("KCODEREG");
		// 校验手机号不能为空
		if (StringUtils.isBlank(mobileNumber)) {
			logger.error("数据检查失败： 用户名为空");
			resMap.put("code", Consts.CHECK_CODE);
			resMap.put("message", Message.CnDescriptionExpression.USER_IS_NULL);
			return resMap;
		}

		// channel
		if (StringUtils.isBlank(channel) || !channelList.contains(channel)) {
			logger.error("数据检查失败：渠道为:" + channel);
			resMap.put("code", Consts.ERROR_CODE);
			resMap.put("message", "渠道参数不正确!");
			return resMap;
		}

		// 非法手机号检查
		boolean flag = mobileNumber.matches(Consts.PHONECHECK);
		if (!flag) {
			logger.error("数据检查失败：  手机号格式不对");
			resMap.put("code", Consts.CHECK_CODE);
			resMap.put("message", Message.CnDescriptionExpression.MOBILE_IS_NON_STANDARD);
			return resMap;
		}

		resMap.put("code", Consts.SUCCESS_CODE);
		resMap.put("message", Consts.SUCCESS_DESCRIBE);
		return resMap;
	}

	/**
	 * 激活k码数据检查
	 * 
	 * @param paramsMap
	 * @return
	 * @throws Exception
	 */
	private Map<String, Object> activateKcodeParamCheck(Map<String, Object> paramsMap) throws Exception {
		Map<String, Object> resMap = new HashMap<String, Object>();
		String mobileNumber = (String) paramsMap.get("mobileNumber");// 用户手机号
		String kCode = (String) paramsMap.get("kCode"); // K码
		String channel = (String) paramsMap.get("channel");
		String salemanMobile = (String) paramsMap.get("salemanMobile");// 销售人员手机号码

		List<String> channelList = new ArrayList<String>();
		channelList.add("LINGDANG");
		channelList.add("WEBSITE");
		channelList.add("KCODEREG");
		channelList.add("LBAndroid");
		channelList.add("LBIOS");

		// 校验手机号不能为空
		if (StringUtils.isBlank(mobileNumber)) {
			logger.error("激活k码数据检查失败： 用户名为空");
			Map<String, Object> errorMap = errorMessageService.getErrorMessage("EM000000007");
			resMap.put("errorMap", errorMap);
			resMap.put("code", Consts.CHECK_CODE);
			resMap.put("message", getErrorMsg(errorMap));
			return resMap;
		}

		// K码
		if (StringUtils.isBlank(kCode)) {
			logger.error("激活k码数据检查失败：kCode为空:" + kCode);
			Map<String, Object> errorMap = errorMessageService.getErrorMessage("EM000000007");
			resMap.put("errorMap", errorMap);
			resMap.put("code", Consts.ERROR_CODE);
			resMap.put("message", getErrorMsg(errorMap));// k码不能为空！
			return resMap;
		}

		// channel
		if (StringUtils.isBlank(channel) || !channelList.contains(channel)) {
			logger.error("数据检查失败：channel为:" + channel);
			Map<String, Object> errorMap = errorMessageService.getErrorMessage("EM000000007");
			resMap.put("errorMap", errorMap);
			resMap.put("code", Consts.ERROR_CODE);
			resMap.put("message", getErrorMsg(errorMap));// 渠道参数不正确!
			return resMap;
		}

		// 非法手机号检查
		boolean flag = mobileNumber.matches(Consts.PHONECHECK);
		if (!flag) {
			logger.error("激活k码数据检查失败：  手机号格式不对");
			Map<String, Object> errorMap = errorMessageService.getErrorMessage("EM000000007");
			resMap.put("errorMap", errorMap);
			resMap.put("code", Consts.ERROR_CODE);
			resMap.put("message", getErrorMsg(errorMap));// 请输入规范的手机号码
			return resMap;
		}

		// 销售人员手机号码校验
		if (salemanMobile != null && !salemanMobile.equals("")) {
			boolean salemanFlag = salemanMobile.matches(Consts.PHONECHECK);
			if (!salemanFlag) {
				logger.error("激活k码数据检查失败：  销售人员手机号格式不对");
				Map<String, Object> errorMap = errorMessageService.getErrorMessage("EM000000025");
				resMap.put("errorMap", errorMap);
				resMap.put("code", Consts.ERROR_CODE);
				resMap.put("message", getErrorMsg(errorMap));// 请输入规范的手机号码
				return resMap;
			}
		}

		resMap.put("code", Consts.SUCCESS_CODE);
		resMap.put("message", Consts.SUCCESS_DESCRIBE);
		return resMap;
	}

	/**
	 * 注册数据检查
	 * 
	 * @param params
	 * @return
	 * @throws Exception
	 */
	private ResultDTO registerCheck(JSONObject params) throws Exception {
		Map<String, String> resMap = new HashMap<>();
		String mobileNumber = params.getString("mobileNumber");// 用户手机号
		String channel = params.getString("channel");

		List<String> channelList = new ArrayList<String>();
		channelList.add("LINGDANG");
		channelList.add("WEBSITE");
		channelList.add("KCODEREG");

		// 校验用户名不能为空
		if (StringUtils.isBlank(mobileNumber)) {
			logger.error("注册数据检查失败： 用户名为空");
			return new ResultDTO(ResultCode.FAILED,
					Message.CnDescriptionExpression.USER_IS_NULL);
		}

		// 非法手机号检查
		boolean flag = mobileNumber.matches(Consts.PHONECHECK);
		if (!flag) {
			logger.error("注册数据检查失败：  手机号格式不对");
			return new ResultDTO(ResultCode.FAILED,
					Message.CnDescriptionExpression.MOBILE_IS_NON_STANDARD);
		}

		// channel
		if (StringUtils.isBlank(channel) || !channelList.contains(channel)) {
			logger.error("数据检查失败：channel为:" + channel);
			return new ResultDTO(ResultCode.FAILED,"渠道参数不正确!");
		}

		// 先判断用户是否存在(目前只针对手机用户)
		int count = userService.phoneIsExisted(mobileNumber);
		if (count > 0) {
			logger.error("注册数据检查失败：  手机号已存在于联币钱包平台");
			resMap.put("code", Consts.CHECK_CODE);
			resMap.put("message", Message.CnDescriptionExpression.USER_IS_EXISTED);
			return new ResultDTO(ResultCode.FAILED,
					Message.CnDescriptionExpression.USER_IS_EXISTED);
		}
		return ResultConstant.SUCCESS;
	}

	/**
	 * 查询理财信息及k码操作激活状态方法数据检查
	 * 
	 * @param paramsMap
	 * @return
	 */
	private Map<String, String> queryReturnFinanceInfoCheck(Map<String, String> paramsMap) throws Exception {
		Map<String, String> resMap = new HashMap<String, String>();
		String channel = paramsMap.get("channel");
		String idcardNo = paramsMap.get("idcardNo");
		String operator = paramsMap.get("operator");

		// channel
		if (StringUtils.isBlank(channel) || !"PHICOMM".equals(channel)) {
			logger.error("数据检查失败：channel为:" + channel);
			resMap.put("code", Consts.ERROR_CODE);
			resMap.put("message", "渠道参数不正确!");
			return resMap;
		}

		if (StringUtils.isBlank(idcardNo)) {
			logger.error("数据检查失败：idcardNo为:" + idcardNo);
			resMap.put("code", Consts.ERROR_CODE);
			resMap.put("message", "卡号参数不正确!");
			return resMap;
		}

		if (StringUtils.isBlank(operator)) {
			logger.error("数据检查失败：operator为:" + operator);
			resMap.put("code", Consts.ERROR_CODE);
			resMap.put("message", "操作员参数不正确!");
			return resMap;
		}

		resMap.put("code", Consts.SUCCESS_CODE);
		resMap.put("message", Consts.SUCCESS_DESCRIBE);
		return resMap;
	}

	/**
	 * 数据检查
	 * 
	 * @param paramsMap
	 * @return
	 * @throws Exception
	 */
	private Map<String, String> orderCancelCheck(Map<String, String> paramsMap) throws Exception {
		Map<String, String> resMap = new HashMap<String, String>();
		String channel = paramsMap.get("channel"); // 平台识别码
		String idcardNo = paramsMap.get("idcardNo"); // 卡号
		String operator = paramsMap.get("operator"); // 操作人员
		// 渠道集合
		List<String> channelList = new ArrayList<String>();
		channelList.add("PHICOMM");
		channelList.add("WEBSITE");
		// 校验卡号不能为空
		if (StringUtils.isBlank(idcardNo)) {
			logger.error("数据检查失败： 卡号为空");
			resMap.put("code", Consts.CHECK_CODE);
			resMap.put("message", "卡号为空");
			return resMap;
		}

		// channel
		if (StringUtils.isBlank(channel) || !channelList.contains(channel)) {
			logger.error("数据检查失败：channel为:" + channel);
			resMap.put("code", Consts.ERROR_CODE);
			resMap.put("message", "渠道参数不正确!");
			return resMap;
		}

		// 操作人员不能为空
		if (StringUtils.isBlank(operator)) {
			logger.error("数据检查失败： 操作人员为空");
			resMap.put("code", Consts.CHECK_CODE);
			resMap.put("message", "操作人员为空");
			return resMap;
		}
		resMap.put("code", Consts.SUCCESS_CODE);
		resMap.put("message", Consts.SUCCESS_DESCRIBE);
		return resMap;
	}

	/**
	 * 获取用户交易记录
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/getFundFlow")
	public void getFundFlow(HttpServletRequest request, HttpServletResponse response) throws Exception{
		Map<String, String> paramsMap = new HashMap<String, String>();
		// 解密请求参数
		String reqString = request.getQueryString();
		if (StringUtils.isBlank(reqString)) {
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "", "参数异常！");
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			return;
		}

		Integer current = 1;
		Integer pageSize = 20;
		reqString = DES3Util.decode(reqString);
		reqString = java.net.URLDecoder.decode(reqString, "UTF-8");
		HashMap<String, Object> reqMap = CommonUtil.jsonObjToHashMap(reqString);

		String mobileNumber = reqMap.get("mobileNumber") == null ? "" : reqMap.get("mobileNumber").toString();
		String channel = reqMap.get("channel") == null ? "" : reqMap.get("channel").toString();
		String startDate = reqMap.get("startDate") == null ? "" : reqMap.get("startDate").toString();
		String endDate = reqMap.get("endDate") == null ? "" : reqMap.get("endDate").toString();
		String currentStr = reqMap.get("current") == null ? "" : reqMap.get("current").toString();
		String pageSizeStr = reqMap.get("pageSize") == null ? "" : reqMap.get("pageSize").toString();

		paramsMap.put("mobileNumber", mobileNumber);
		paramsMap.put("channel", channel);

		Map<String, String> checkMap = defCheck(paramsMap);
		if (null == checkMap || !Consts.SUCCESS_CODE.equals(checkMap.get("code"))) {
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), checkMap.get("code"), "",
					checkMap.get("message"));
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			return;
		}

		// 获取用户ID
		Map<String, Object> userMap = new HashMap<String, Object>();
		userMap.put("mobile", mobileNumber);
		User user = userService.getUserByParm(userMap);
		String userId = String.valueOf(user.getId());

		if (StringUtils.isNotBlank(currentStr)) {
			current = Integer.parseInt(currentStr);
		}
		if (StringUtils.isNotBlank(pageSizeStr)) {
			pageSize = Integer.parseInt(pageSizeStr);
		}

		String transCode = "E330004";
		// 设置报文体报文数据
		Map<String, Object> pageModelForWallet = new HashMap<String, Object>();
		pageModelForWallet.put("userId", userId); // 用户id
		// TODO 获取手机支持的产品id字符串
		// 产品类型：101 e计划(90天)，102 e贷通，103 涨薪宝, 104 e计划(365天),多个产品之间用英文【,】进行分隔
		// pageModelForWallet.put("productType", "101,103,104");
		String financeIdString = financeService.getFinanceString();
		pageModelForWallet.put("productType", financeIdString);
		// pageModelForWallet.put("productType", Consts.GQB); //
		// 产品类型：103（鼓钱包）
		pageModelForWallet.put("current", current); // 当前页
		pageModelForWallet.put("pageSize", pageSize); // 页大小
		// 资金类型设置 （类型两边有空格）
		// 鼓钱包理财人展现资金类型(1、活动返还;2、网站充值;3、提现;4、提现手续费;5、加入e计划;6、加入e贷通;7、本金回款;8、收益回款;
		// 9、转让收入;10、转让手续费;25、冲账;30、提现申请;31、加入涨薪宝;34、鼓钱包充值;35、邀请返现;37、签约中资金退出;)
		pageModelForWallet.put("withdrawFundType", " '3','4' ");// 提现类型（类型两边有空格）
		pageModelForWallet.put("rechargeFundType", " '1','2','34' ");// 充值类型（类型两边有空格）
		pageModelForWallet.put("rechargeWithdrawFundType", " '1','2','3','4','34' ");// 充值提现类型（类型两边有空格）
		// 30、提现申请不展示
		pageModelForWallet.put("outFundType", " '5','10','31','48','56' ");// 主账户支出资金流水类型（类型两边有空格）
		pageModelForWallet.put("inFundType", " '1','7','8','9','25','35','37','49','51' ");// 主账户收入资金流水类型（类型两边有空格）
		pageModelForWallet.put("allFundType",
				" '1','5','6','7','8','9','10','25','31','35','37','48','49','51','56' ");// 主账户收入支出资金流水类型（类型两边有空格）

		pageModelForWallet.put("inOrOut", "");//// 抽取条件（无值--全部、in--收入、out--支出）

		pageModelForWallet.put("startDate", startDate);//// 抽取条件（无值--全部、in--收入、out--支出）
		pageModelForWallet.put("endDate", endDate);//// 抽取条件（无值--全部、in--收入、out--支出）

		// 构建json字符串
		String jsonStr = CommonUtil.constructJsonStr(transCode, userId, pageModelForWallet);

		// 调用核心接口E330004取得资金流水详情
		ResultDTO result = this.walletService.getFundFlowDetail(jsonStr, current, pageSize);
		ResponseUtil.write(response,  result);
	}

	/**
	 * 获取用户每天收益记录（活期）
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/getDayIncomeFlow")
	public void getDayIncomeFlow(HttpServletRequest request, HttpServletResponse response) {
		Map<String, String> paramsMap = new HashMap<String, String>();
		// 解密请求参数
		String reqString = request.getQueryString();
		if (StringUtils.isBlank(reqString)) {
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "", "参数异常！");
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			return;
		}

		Integer current = 1;
		Integer pageSize = 20;
		try {
			reqString = DES3Util.decode(reqString);
			reqString = java.net.URLDecoder.decode(reqString, "UTF-8");
			HashMap<String, Object> reqMap = CommonUtil.jsonObjToHashMap(reqString);

			String mobileNumber = reqMap.get("mobileNumber") == null ? "" : reqMap.get("mobileNumber").toString();
			String channel = reqMap.get("channel") == null ? "" : reqMap.get("channel").toString();
			String currentStr = reqMap.get("current") == null ? "" : reqMap.get("current").toString();
			String pageSizeStr = reqMap.get("pageSize") == null ? "" : reqMap.get("pageSize").toString();

			paramsMap.put("mobileNumber", mobileNumber);
			paramsMap.put("channel", channel);

			Map<String, String> checkMap = defCheck(paramsMap);
			if (null == checkMap || !Consts.SUCCESS_CODE.equals(checkMap.get("code"))) {
				String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), checkMap.get("code"), "",
						checkMap.get("message"));
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			}

			// 获取用户ID
			Map<String, Object> userMap = new HashMap<String, Object>();
			userMap.put("mobile", mobileNumber);
			User user = userService.getUserByParm(userMap);
			String userId = String.valueOf(user.getId());

			if (StringUtils.isNotBlank(currentStr)) {
				current = Integer.parseInt(currentStr);
			}
			if (StringUtils.isNotBlank(pageSizeStr)) {
				pageSize = Integer.parseInt(pageSizeStr);
			}

			Map<String, Object> map = new HashMap<String, Object>();
			map.put("pageSize", pageSize);
			map.put("current", current);
			map.put("userId", userId);
			map.put("finaceId", "1");

			// 查询余额宝历史收益列表
			String result = depositService.queryIncomeStatementList(map);
			CommonUtil.responseJson(result, response);
		} catch (Exception e) {
			logger.debug("======异常发生======" + CommonUtil.printStackTraceToString(e));

			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE,
					Consts.ErrorMsg.MSG00001, Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		}
	}

	/**
	 * 获取用户每天收益记录（定期）
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/getFixIncomeFlow")
	public void getFixIncomeFlow(HttpServletRequest request, HttpServletResponse response) {
		Map<String, String> paramsMap = new HashMap<String, String>();
		// 解密请求参数
		String reqString = request.getQueryString();
		if (StringUtils.isBlank(reqString)) {
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "", "参数异常！");
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			return;
		}

		Integer current = 1;
		Integer pageSize = 20;
		try {
			reqString = DES3Util.decode(reqString);
			reqString = java.net.URLDecoder.decode(reqString, "UTF-8");
			HashMap<String, Object> reqMap = CommonUtil.jsonObjToHashMap(reqString);

			String mobileNumber = reqMap.get("mobileNumber") == null ? "" : reqMap.get("mobileNumber").toString();
			String channel = reqMap.get("channel") == null ? "" : reqMap.get("channel").toString();
			String currentStr = reqMap.get("current") == null ? "" : reqMap.get("current").toString();
			String pageSizeStr = reqMap.get("pageSize") == null ? "" : reqMap.get("pageSize").toString();

			paramsMap.put("mobileNumber", mobileNumber);
			paramsMap.put("channel", channel);

			Map<String, String> checkMap = defCheck(paramsMap);
			if (null == checkMap || !Consts.SUCCESS_CODE.equals(checkMap.get("code"))) {
				String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), checkMap.get("code"), "",
						checkMap.get("message"));
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			}

			// 获取用户ID
			Map<String, Object> userMap = new HashMap<String, Object>();
			userMap.put("mobile", mobileNumber);
			User user = userService.getUserByParm(userMap);
			String userId = String.valueOf(user.getId());

			if (StringUtils.isNotBlank(currentStr)) {
				current = Integer.parseInt(currentStr);
			}
			if (StringUtils.isNotBlank(pageSizeStr)) {
				pageSize = Integer.parseInt(pageSizeStr);
			}

			String transCode = "E330010";
			// 设置报文体报文数据
			Map<String, Object> pageModelForWallet = new HashMap<String, Object>();

			pageModelForWallet.put("userId", userId); // 用户ID
			pageModelForWallet.put("creditCId", ""); // 债权id
			pageModelForWallet.put("pageSize", pageSize); // 页大小
			// pageModelForWallet.put("bId", ""); // 标的id
			pageModelForWallet.put("current", current); // 当前页数
			pageModelForWallet.put("reseiptStates", "1,3,5");

			// 构建json字符串
			String jsonStr = CommonUtil.constructJsonStr(transCode, userId, pageModelForWallet);

			// 调用核心接口取得我的收款分期明细
			String result = this.walletService.getRepaymentDetail(jsonStr);
			JSONObject resultObject = JSONObject.parseObject(result);
			JSONArray list = resultObject.getJSONArray("list");
			JSONArray newlist = new JSONArray();
			resultObject.remove("list");
			if (resultObject.getIntValue("listSize") > 0) {
				for (int i = 0; i < resultObject.getIntValue("listSize"); i++) {
					JSONObject retobj = new JSONObject();
					retobj.put("earningsDate", list.getJSONObject(i).get("needReceiptDay"));
					retobj.put("incomeAmount", list.getJSONObject(i).get("hadReceiptInterest"));
					newlist.add(retobj);
				}
			}
			resultObject.put("list", newlist);

			CommonUtil.responseJson(resultObject.toString(), response);
		} catch (Exception e) {
			logger.debug("======异常发生======" + CommonUtil.printStackTraceToString(e));

			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE,
					Consts.ErrorMsg.MSG00001, Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		}
	}

	/**
	 * 推荐理财产品
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/getRecommendProduct")
	public void getRecommendProduct(HttpServletRequest request, HttpServletResponse response) {
		Map<String, String> paramsMap = new HashMap<String, String>();
		String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
		// 解密请求参数
		String reqString = request.getQueryString();
		if (StringUtils.isBlank(reqString)) {
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "", "参数异常！");
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			return;
		}

		try {
			reqString = DES3Util.decode(reqString);
			reqString = java.net.URLDecoder.decode(reqString, "UTF-8");
			HashMap<String, Object> reqMap = CommonUtil.jsonObjToHashMap(reqString);

			String mobileNumber = reqMap.get("mobileNumber") == null ? "" : reqMap.get("mobileNumber").toString();
			String channel = reqMap.get("channel") == null ? "" : reqMap.get("channel").toString();

			paramsMap.put("mobileNumber", mobileNumber);
			paramsMap.put("channel", channel);

			Map<String, String> checkMap = defCheck(paramsMap);
			if (null == checkMap || !Consts.SUCCESS_CODE.equals(checkMap.get("code"))) {
				String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), checkMap.get("code"), "",
						checkMap.get("message"));
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			}

			List<Scattered> scatteredList = loanService.queryWxAndAppLoan();

			/**
			 * 剩余金额小于起头金额，返回100% 当产品已经超过下架时间，返回100%
			 */
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			if (scatteredList != null && scatteredList.size() > 0) {
				Scattered sc = scatteredList.get(0);
				Map<String, Object> scMap = new HashMap<String, Object>();
				// id
				scMap.put("scatteredLoanId", sc.getId());
				// 产品名称
				scMap.put("productName", sc.getProductName());
				// 年利率
				scMap.put("annualRate", sc.getAnnualRate());
				// 剩余金额
				scMap.put("remanAmount", sc.getRemanAmount());
				// 上架金额
				scMap.put("saleTotalAmount", sc.getSaleTotalAmount());
				// 起投金额
				scMap.put("investMinAmount", sc.getInvestMinAmount());
				// 理财周期（单位月，如：1表示1个月期，活期为0）
				String period = "0";
				if ("1".equals(sc.getSellingType())) {
					period = String.valueOf(sc.getRemanPeriods());
				}
				scMap.put("period", period);
				// 投资进度%
				scMap.put("finishedRatio",
						DecimalFormatUtil.getDecimalFormat0(BigDecimal.ONE.compareTo(sc.getFinishedRatio()) > 0
								&& BigDecimal.ZERO.compareTo(sc.getFinishedRatio()) < 0 ? BigDecimal.ONE
										: sc.getFinishedRatio()));
				// 上架时间
				scMap.put("startSellingTime",
						sc.getStartSellingTime() == null ? "" : sdf.format(sc.getStartSellingTime()));

				// O2O访问RSA加签
				Map<String, String> rsaMap = new HashMap<String, String>();
				rsaMap.put("mobileNumber", mobileNumber);
				rsaMap.put("channel", channel);
				String encrypt_key = "";
				try {
					encrypt_key = RSARequestO2O.getPublick_Key_Encrypt(rsaMap);
				} catch (Exception e1) {
					e1.printStackTrace();
				}
				// 定期的场合
				if ("1".equals(sc.getSellingType())) {
					scMap.put("url", basePath + "/wxproduct/goDemandProductIndex?encrypt_key=" + encrypt_key);

					Map<String, Object> map = new HashMap<String, Object>();
					map.put("loanId", sc.getBidId());
					map.put("planId", sc.getPlanId());
					map.put("sloanId", sc.getId());
					map.put("contactAmount", sc.getContactAmount());
					map.put("cpType", URLEncoder.encode(sc.getProductName()));
					String param = CommonUtil.getParam(map);
					scMap.put("proUrl",
							basePath + "/wxproduct/goProductBuy?" + param + "&abc=1&encrypt_key=" + encrypt_key);
				}
				// 活期的场合
				if ("2".equals(sc.getSellingType())) {
					scMap.put("url", basePath + "/wxproduct/goDemandProductIndex?encrypt_key=" + encrypt_key);
					scMap.put("proUrl", basePath + "/wxproduct/goDemandOrderConfirmation?id=" + sc.getId()
							+ "&abc=1&encrypt_key=" + encrypt_key);
				}

				String result = CommonUtil.setResultStringCn(scMap, Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE, "");
				// 处理返回结果
				CommonUtil.responseJson(result, response);
			} else {
				// 处理返回结果
				String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.CHECK_CODE, "",
						"未获取产品信息！");
				CommonUtil.responseJson(result, response);
				return;
			}
		} catch (Exception e) {
			logger.debug("======异常发生======" + CommonUtil.printStackTraceToString(e));

			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE,
					Consts.ErrorMsg.MSG00001, Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		}
	}

	private String nullToBlank(Object obj) {
		if (obj == null) {
			return "";
		}
		return obj.toString();
	}

	private Map<String, String> addUserActivityCheck(Map<String, String> paramsMap) throws Exception {
		Map<String, String> resMap = new HashMap<String, String>();
		String channel = paramsMap.get("channel"); // 平台识别码
		String idcardNo = paramsMap.get("idcardNo"); // 卡号
		String model = paramsMap.get("model");
		String orderId = paramsMap.get("orderId");
		// 渠道集合
		List<String> channelList = new ArrayList<String>();
		channelList.add("PHICOMM");
		// 校验卡号不能为空
		if (StringUtils.isBlank(idcardNo)) {
			logger.error("数据检查失败： 卡号为空");
			resMap.put("code", Consts.CHECK_CODE);
			resMap.put("message", "卡号为空");
			return resMap;
		}
		// 校验型号不能为空
		if (StringUtils.isBlank(model)) {
			logger.error("数据检查失败： 型号为空");
			resMap.put("code", Consts.CHECK_CODE);
			resMap.put("message", "型号为空");
			return resMap;
		}
		// 校验订单号不能为空
		if (StringUtils.isBlank(orderId)) {
			logger.error("数据检查失败：订单号为空");
			resMap.put("code", Consts.CHECK_CODE);
			resMap.put("message", "订单号为空");
			return resMap;
		}

		// channel
		if (StringUtils.isBlank(channel) || !channelList.contains(channel)) {
			logger.error("数据检查失败：channel为:" + channel);
			resMap.put("code", Consts.ERROR_CODE);
			resMap.put("message", "渠道参数不正确!");
			return resMap;
		}

		resMap.put("code", Consts.SUCCESS_CODE);
		resMap.put("message", Consts.SUCCESS_DESCRIBE);
		return resMap;
	}

	/**
	 * 记录卡号与型号的绑定关系（斐讯接口）
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/addCardNoAndModelInfo")
	public void addCardNoAndModelInfo(HttpServletRequest request, HttpServletResponse response) {
		// Map<String, String> paramsMap = new HashMap<String, String>();
		//
		// // 解密请求参数
		// String reqString = request.getQueryString();
		// if (StringUtils.isBlank(reqString)) {
		// String result = CommonUtil.setResultStringCn(
		// new HashMap<String, Object>(), Consts.ERROR_CODE, "",
		// "参数异常！");
		// // 处理返回结果
		// CommonUtil.responseJsonNotEncrypt(result, response);
		// return;
		// }
		//
		// try {
		// reqString = java.net.URLDecoder.decode(reqString, "UTF-8");
		// HashMap<String, Object> reqMap =
		// CommonUtil.jsonObjToHashMap(reqString);
		//
		// //卡号
		// String idcardNo = reqMap.get("idcardNo") == null ? "" :
		// reqMap.get("idcardNo").toString();
		// //渠道
		// String channel = reqMap.get("channel") == null ? "" :
		// reqMap.get("channel").toString();
		// //型号
		// String model = reqMap.get("model") == null ? "" :
		// reqMap.get("model").toString();
		// //订单号
		// String orderId = reqMap.get("orderId") == null ? "" :
		// reqMap.get("orderId").toString();
		//
		// paramsMap.put("idcardNo", idcardNo);
		// paramsMap.put("channel", channel);
		// paramsMap.put("model", model);
		// paramsMap.put("orderId", orderId);
		//
		// Map<String, String> checkMap = addUserActivityCheck(paramsMap);
		// if (null == checkMap
		// || !Consts.SUCCESS_CODE.equals(checkMap.get("code"))) {
		// String result = CommonUtil.setResultStringCn(
		// new HashMap<String, Object>(), checkMap.get("code"),
		// "", checkMap.get("message"));
		// // 处理返回结果
		// CommonUtil.responseJsonNotEncrypt(result, response);
		// return;
		// }
		// // 记录卡号与型号的绑定关系
		// Map<String, String> kparamsMap = new HashMap<String, String>();
		// kparamsMap.put("idcardNo", idcardNo);
		// kparamsMap.put("model", model);
		// kparamsMap.put("orderId", orderId);
		//
		// Map<String, Object> retMap =
		// this.activityService.addCardNoAndModelInfo(kparamsMap);
		//
		// String result = JsonUtil.getJsonStringFromMap(retMap);
		// CommonUtil.responseJsonNotEncrypt(result, response);
		// } catch (Exception e) {
		// e.printStackTrace();
		// logger.error("记录卡号与型号的绑定关系异常:" +
		// CommonUtil.printStackTraceToString(e));
		// String result = CommonUtil.setResultStringCn(
		// new HashMap<String, Object>(), Consts.ERROR_CODE, "",
		// Message.CnDescriptionExpression.BUSINESSE_ERROR);
		// // 处理返回结果
		// CommonUtil.responseJsonNotEncrypt(result, response);
		// }
	}

	/**
	 * 
	 * @Description: 添加微商推送数据
	 * @param response
	 * @return void
	 * @throws @author
	 *             wuhan
	 * @date 2016-7-7
	 */
	@RequestMapping(value = "/pushWbData", method = { RequestMethod.POST })
	public void pushWbData(@RequestBody PushData datas, HttpServletResponse response) {
		// 1.获取推送数据
		int listSizeStr = datas.getListSize();
		List<Map<String, Object>> list = datas.getList();
		List<Map<String, Object>> resultList = null;
		String result = "";

		List<Map<String, String>> errorList = new ArrayList<Map<String, String>>();// 错误信息返回列表
		if (list != null) {
			resultList = list;
		}
		if (listSizeStr < 1 || (null == resultList || (null != resultList && resultList.size() < 1))) {
			// 暂无数据
			result += CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.CHECK_CODE, "数据为空！", "数据为空！");
			// 处理返回结果
			CommonUtil.responseJsonNotEncrypt(result, response);
			return;
		}
		// 2.校验数据规范
		for (Map map : resultList) {
			if (null != map) {
				Map<String, String> checkMap = checkpwbParams(map);
				if (null != checkMap) {
					errorList.add(checkMap);// 添加错误信息
					continue;
				}

				// 3.判断卡号是存在(存在提示此数据已存在，反之添加数据)
				String cardNo = map.get("cardNo").toString();
				try {
					UserActivityKeyCode userActivityKeyCode = activityService.queryUserActivityKeyCodeByCardNo(map);
					if (userActivityKeyCode != null) {

						Map<String, String> resMap = new HashMap<String, String>();
						resMap.put("cardNo", cardNo);
						resMap.put("rescode", Consts.BUSINESSE_CODE);
						resMap.put("resmsg_cn", "cardNo已存在!");
						resMap.put("resmsg", "params.cardNo.exist");
						errorList.add(resMap);// 添加错误信息
						continue;
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					Map<String, String> resMap = new HashMap<String, String>();
					resMap.put("cardNo", cardNo);
					resMap.put("rescode", Consts.ERROR_CODE);
					resMap.put("resmsg_cn", Message.CnDescriptionExpression.BUSINESSE_ERROR);
					resMap.put("resmsg", "businesse.error");
					errorList.add(resMap);// 添加错误信息

					continue;
				}

				// 4.数据入库
				try {
					// 5.查看k码合作模式，设置其合作模式
					// int
					// pushwsType=Integer.valueOf(activityService.findParamValueByName("key_code_pushdata_ws_type"));
					activityService.addWbActivityKeyCodeData(map);
				} catch (DuplicateKeyException e) {
					logger.error("ldActivity.pushWbData.Exception:{}", e);
					Map<String, String> resMap = new HashMap<String, String>();
					resMap.put("cardNo", cardNo);
					resMap.put("rescode", Consts.BUSINESSE_CODE);
					resMap.put("resmsg_cn", "cardNo已存在!");
					resMap.put("resmsg", "params.cardNo.exist");
					errorList.add(resMap);// 添加错误信息
					continue;
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					Map<String, String> resMap = new HashMap<String, String>();
					resMap.put("cardNo", cardNo);
					resMap.put("rescode", Consts.ERROR_CODE);
					resMap.put("resmsg_cn", Message.CnDescriptionExpression.BUSINESSE_ERROR);
					resMap.put("resmsg", "businesse.error");
					errorList.add(resMap);// 添加错误信息

					continue;
				}
			}
		}
		if (errorList.size() == 0) {
			result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.SUCCESS_CODE,
					Consts.SUCCESS_DESCRIBE, "推送成功");
		} else {
			if (errorList.size() == resultList.size()) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("errorList", errorList);
				result += CommonUtil.setResultStringCn(map, Consts.FAILURE_CODE, "failure", "推送失败");
			} else {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("errorList", errorList);
				result += CommonUtil.setResultStringCn(map, Consts.PARTIAL_FAILURE_CODE, "partial.failure", "部分失败");
			}
		}
		CommonUtil.responseJsonNotEncrypt(result, response);

	}

	/**
	 * 
	 * @Description: 校验微商推送数据
	 * @param @param
	 *            paramsMap
	 * @return Map<String,String>
	 * @throws @author
	 *             wuhan
	 * @date 2016-7-7
	 */
	private Map<String, String> checkpwbParams(Map map) {
		Map<String, String> resMap = new HashMap<String, String>();
		String snNo = "";
		String cardNo = "";
		String orderId = "";
		String orderTime = "";
		String channel = "";
		try {
			cardNo = map.get("cardNo").toString(); // 卡号
			snNo = map.get("snNo").toString(); // 设备号
			orderId = map.get("orderId").toString(); // 订单号
			orderTime = map.get("orderTime").toString(); // 订单时间
			channel = map.get("channel").toString(); // 渠道编号//设备号
		} catch (Exception e) {
			logger.error("ldActivity.pushWbData,数据检查失败：参数缺省!param:{" + map.toString() + "}");
			resMap.put("param", map.toString());
			resMap.put("rescode", Consts.CHECK_CODE);
			resMap.put("resmsg_cn", "参数名错误!");
			resMap.put("resmsg", "params.is.miss");
			return resMap;
		}

		if (StringUtils.isBlank(cardNo)) {
			logger.error("ldActivity.pushWbData,数据检查失败：cardNo不能为空!param:{" + map.toString() + "}");
			resMap.put("param", map.toString());
			resMap.put("rescode", Consts.CHECK_CODE);
			resMap.put("resmsg_cn", "必填项cardNo不能为空!");
			resMap.put("resmsg", "params.cardNo.is.null");
			return resMap;
		} else {
			if (cardNo.length() != 10) {
				logger.error("数据检查失败：卡号长度不是10位");
				resMap.put("cardNo", cardNo);
				resMap.put("rescode", Consts.CHECK_CODE);
				resMap.put("resmsg_cn", "cardNo长度不是10位!");
				resMap.put("resmsg", "params.cardNo.length.must.be.10");
				return resMap;
			}
		}

		if (StringUtils.isNotBlank(snNo)) {
			if (snNo.length() > 64) {
				logger.error("ldActivity.pushWbData,数据检查失败：snNo超出最大长度!param:{" + map.toString() + "}");
				resMap.put("cardNo", cardNo);
				resMap.put("rescode", Consts.CHECK_CODE);
				resMap.put("resmsg_cn", "snNo超出最大长度!");
				resMap.put("resmsg", "params.snNo.over.max.length");
				return resMap;
			}
		}

		if (StringUtils.isNotBlank(orderId)) {
			if (orderId.length() > 64) {
				logger.error("数据检查失败：orderId超出最大长度");
				resMap.put("cardNo", cardNo);
				resMap.put("rescode", Consts.CHECK_CODE);
				resMap.put("resmsg_cn", "orderId超出最大长度!");
				resMap.put("resmsg", "");
				return resMap;
			}
		}

		if (StringUtils.isBlank(orderTime)) {
			logger.error("数据检查失败：orderTime不能为空");
			resMap.put("cardNo", cardNo);
			resMap.put("rescode", Consts.CHECK_CODE);
			resMap.put("message", "必填项orderTime不能为空!");
			resMap.put("resmsg", "params.orderTime.is.null");
			return resMap;
		}
		boolean flag = DateUtil.isDateStringValid(orderTime, fmt);
		if (flag == false) {
			logger.error("数据检查失败：orderTime格式错误");
			resMap.put("cardNo", cardNo);
			resMap.put("rescode", Consts.CHECK_CODE);
			resMap.put("message", "必填项orderTime格式错误!应为yyyy-MM-dd HH:mm:ss");
			resMap.put("resmsg", "params.orderTime.formate.error");
			return resMap;
		}

		if (StringUtils.isBlank(channel)) {
			logger.error("数据检查失败：channel不能为空");
			resMap.put("cardNo", cardNo);
			resMap.put("rescode", Consts.CHECK_CODE);
			resMap.put("message", "必填项channel不能为空!");
			resMap.put("resmsg", "params.channel.is.null");
			return resMap;
		}

		if (!channel.equalsIgnoreCase("微商")) {
			logger.error("数据检查失败：channel类型错误");
			resMap.put("cardNo", cardNo);
			resMap.put("rescode", Consts.CHECK_CODE);
			resMap.put("message", "channel类型错误!");
			resMap.put("resmsg", "params.channel.type.error");
			return resMap;
		}
		return null;
	}

	@RequestMapping(value = "/checkMoblie")
	public void checkMoblie(HttpServletRequest request, HttpServletResponse response)
			throws IllegalArgumentException, IllegalAccessException {
		logger.info("==========激活k码校验 手机号接口 start");
		try {
			Map<String, String> reqMap = CommonUtil.decryptParamters(request);
			// 用户手机号
			String phoneNum = nullToBlank(reqMap.get("phoneNum"));
			logger.info("==========激活k码校验 手机号接口 参数phoneNum:" + phoneNum);
			// 手机k码流程
			Map<String, Object> mobileKcodeMsgMap = kcodeChannelService.mobileKCode("验证联通手机号", phoneNum, "2");
			if (mobileKcodeMsgMap != null) {
				String result = CommonUtil.setResultStringCn(mobileKcodeMsgMap, Consts.CHECK_CODE, "",
						getErrorMsg(mobileKcodeMsgMap));
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			}

			// // 判断联通手机号码是否激活过k码
			// Map<String, Object> unionParamMap=new HashMap<String, Object>();
			// unionParamMap.put("unionMobile",phoneNum);
			// List<UserLDActivityInfo> activityInfoByUnionMobileList=
			// activityService.findActivityInfoByParm(unionParamMap);//通过联通手机号码激活信息
			//
			// if(null!=activityInfoByUnionMobileList &&
			// activityInfoByUnionMobileList.size() > 0){
			// //提示信息修改
			// Map<String, Object>
			// errorMap=errorMessageService.getErrorMessage("EM000000023");
			// String result = CommonUtil.setResultStringCn(
			// errorMap, Consts.CHECK_CODE, "",
			// getErrorMsg(errorMap));
			// // 处理返回结果
			// CommonUtil.responseJson(result, response);
			// return;
			// }

		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.info("==========激活k码校验 手机号接口 异常：" + e.getMessage());
			Map<String, Object> errorMap = errorMessageService.getErrorMessage("EM000000021");

			String result = CommonUtil.setResultStringCn(errorMap, Consts.CHECK_CODE, "", getErrorMsg(errorMap));
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		}
		logger.info("==========激活k码校验 手机号接口 end");
		// 处理返回结果
		String result = CommonUtil.setResultStringCn(new HashMap(), Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE,
				Consts.SUCCESS_DESCRIBE);
		CommonUtil.responseJson(result, response);
	}

	@RequestMapping(value = "/querySaleManRecord")
	public void querySaleManRecord(HttpServletRequest request, HttpServletResponse response)
			throws IllegalArgumentException, IllegalAccessException {
		logger.info("==========查询会员销售记录 start");
		Map<String, Object> rtnMap = new HashMap<String, Object>();
		try {
			Map<String, String> reqMap = CommonUtil.decryptParamters(request);
			// 用户手机号
			String mobileNumber = nullToBlank(reqMap.get("mobileNumber"));
			String currentPageStr = reqMap.get(Consts.Page.PAGE_CURRENT_NAME);// 当前页
			String pageSizeStr = reqMap.get(Consts.Page.PAGE_SIZE_NAME);// 页大小
			Integer current = 1;
			Integer pageSize = 10;
			// 分页参数
			if (currentPageStr != null && !("".equals(currentPageStr))) {
				current = Integer.parseInt(currentPageStr);
			}
			if (pageSizeStr != null && !("".equals(pageSizeStr))) {
				pageSize = Integer.parseInt(pageSizeStr);
			}
			logger.info("==========查询会员销售记录 参数mobileNumber:" + mobileNumber);
			// 查询会员销售记录
			Map<String, Object> paraMap = new HashMap<String, Object>();
			paraMap.put("inviterAccount", mobileNumber);
			paraMap.put("current", current);
			paraMap.put("pageSize", pageSize);

			int totalNum = kcodeChannelService.querySalesmanMonthRecordCount(paraMap);
			if (totalNum < 1) {
				rtnMap.put("list", new ArrayList<Map<String, Object>>());
				rtnMap.put("rescode", Consts.SUCCESS_CODE);
				rtnMap.put("resmsg_cn", "查询成功");
				rtnMap.put("listSize", 0);
				rtnMap.put("totlePages", 0);
				rtnMap.put("current", current);
				rtnMap.put("totalNum", 0);
				String result = JsonUtil.getJsonStringFromMap(rtnMap);
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			}

			int totlePages = 0;
			if (totalNum % Integer.valueOf(pageSize) == 0) {
				totlePages = totalNum / Integer.valueOf(pageSize);
			} else {
				totlePages = totalNum / Integer.valueOf(pageSize) + 1;
			}

			List<SalesmanMonthRecord> resultList = kcodeChannelService.querySalesmanMonthRecord(paraMap);
			if (null == resultList || resultList.size() < 1) {
				rtnMap.put("list", new ArrayList<Map<String, Object>>());
				rtnMap.put("rescode", Consts.SUCCESS_CODE);
				rtnMap.put("resmsg_cn", "查询成功");
				rtnMap.put("listSize", 0);
				rtnMap.put("totlePages", 0);
				rtnMap.put("current", current);
				rtnMap.put("totalNum", 0);
				String result = JsonUtil.getJsonStringFromMap(rtnMap);
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			}

			rtnMap.put("totlePages", totlePages);
			rtnMap.put("current", current);
			rtnMap.put("totalNum", totalNum);
			rtnMap.put("list", resultList);
			rtnMap.put("rescode", Consts.SUCCESS_CODE);
			rtnMap.put("resmsg_cn", "查询成功");
			rtnMap.put("listSize", resultList.size());

		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.info("==========查询会员销售记录接口异常：" + e.getMessage());
			Map<String, Object> errorMap = errorMessageService.getErrorMessage("EM000000025");

			String result = CommonUtil.setResultStringCn(errorMap, Consts.CHECK_CODE, "", getErrorMsg(errorMap));
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		}
		logger.info("==========查询会员销售记录 end");
		String result = JsonUtil.getJsonStringFromMap(rtnMap);
		// 处理返回结果
		CommonUtil.responseJson(result, response);
	}

	@RequestMapping(value = "/querySaleManRecordByDate")
	public void querySaleManRecordByDate(HttpServletRequest request, HttpServletResponse response)
			throws IllegalArgumentException, IllegalAccessException {
		logger.info("==========根据月份查询会员销售记录 start");
		Map<String, Object> rtnMap = new HashMap<String, Object>();
		try {
			Map<String, String> reqMap = CommonUtil.decryptParamters(request);
			// 用户手机号
			String mobileNumber = nullToBlank(reqMap.get("mobileNumber"));
			String saleDate = nullToBlank(reqMap.get("saleDate"));
			String currentPageStr = reqMap.get(Consts.Page.PAGE_CURRENT_NAME);// 当前页
			String pageSizeStr = reqMap.get(Consts.Page.PAGE_SIZE_NAME);// 页大小
			Integer current = 1;
			Integer pageSize = 10;
			// 分页参数
			if (currentPageStr != null && !("".equals(currentPageStr))) {
				current = Integer.parseInt(currentPageStr);
			}
			if (pageSizeStr != null && !("".equals(pageSizeStr))) {
				pageSize = Integer.parseInt(pageSizeStr);
			}

			logger.info("==========根据月份查询会员销售记录 参数mobileNumber:" + mobileNumber);

			// 查询会员销售记录
			Map<String, Object> paraMap = new HashMap<String, Object>();
			paraMap.put("inviterAccount", mobileNumber);
			paraMap.put("saleDate", saleDate);
			paraMap.put("current", current);
			paraMap.put("pageSize", pageSize);

			int totalNum = kcodeChannelService.querySaleManRecordListByDateCount(paraMap);
			if (totalNum < 1) {
				rtnMap.put("list", new ArrayList<Map<String, Object>>());
				rtnMap.put("rescode", Consts.SUCCESS_CODE);
				rtnMap.put("resmsg_cn", "查询成功");
				rtnMap.put("listSize", 0);
				rtnMap.put("totlePages", 0);
				rtnMap.put("current", current);
				rtnMap.put("totalNum", 0);
				String result = JsonUtil.getJsonStringFromMap(rtnMap);
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			}

			int totlePages = 0;
			if (totalNum % Integer.valueOf(pageSize) == 0) {
				totlePages = totalNum / Integer.valueOf(pageSize);
			} else {
				totlePages = totalNum / Integer.valueOf(pageSize) + 1;
			}

			// List<Map<String, Object>>
			// resultList=kcodeChannelService.querySetSaleManRecordListByDate(kcodeChannelService.querySaleManRecordListByDate(paraMap));

			List<SalesmanRecord> resultList = kcodeChannelService.querySaleManRecordListByDate(paraMap);
			if (null == resultList || resultList.size() < 1) {
				rtnMap.put("list", new ArrayList<Map<String, Object>>());
				rtnMap.put("rescode", Consts.SUCCESS_CODE);
				rtnMap.put("resmsg_cn", "查询成功");
				rtnMap.put("listSize", 0);
				rtnMap.put("totlePages", 0);
				rtnMap.put("current", current);
				rtnMap.put("totalNum", 0);
				String result = JsonUtil.getJsonStringFromMap(rtnMap);
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			}

			rtnMap.put("totlePages", totlePages);
			rtnMap.put("current", current);
			rtnMap.put("totalNum", totalNum);
			rtnMap.put("rescode", Consts.SUCCESS_CODE);
			rtnMap.put("resmsg_cn", "查询成功");
			rtnMap.put("listSize", resultList.size());
			rtnMap.put("list", resultList);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.info("==========根据月份查询会员销售记录接口 异常：" + e.getMessage());
			Map<String, Object> errorMap = errorMessageService.getErrorMessage("EM000000021");

			String result = CommonUtil.setResultStringCn(errorMap, Consts.CHECK_CODE, "", getErrorMsg(errorMap));
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		}
		logger.info("==========根据月份查询会员销售记录接口 end");
		// 处理返回结果
		String result = JsonUtil.getJsonStringFromMap(rtnMap);
		CommonUtil.responseJson(result, response);
	}
	
	
	/**
	 * 
	 * @Description: 斐讯 渠道信息及卡号信息导入接口
	 * @param request
	 * @param response
	 * @return
	 * @author wuhan	
	 * @date 2016-12-19 14:50:00
	 */
    @RequestMapping(value = "/importKcodeInfo")
	@ResponseBody
	public void importKcodeInfo(HttpServletRequest request,
			HttpServletResponse response) {
    	
    	String loggerInfo="渠道及卡号信息导入接口 ";
    	
		logger.info(loggerInfo+"start");
		
		//1.获取请求参数
		String reqString = request.getQueryString();
		if (StringUtils.isBlank(reqString)) {
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.CHECK_CODE, "", "参数不能为空！");
			// 处理返回结果
			CommonUtil.responseJsonNotEncrypt(result, response);
			return;
		}
		
		try {
			reqString = java.net.URLDecoder.decode(reqString, "UTF-8");
			logger.info(loggerInfo+"请求参数:"+reqString);
			JSONObject jsonParam = JSONObject.parseObject(reqString);
			//2.校验参数合法性
			String validMsg=validParams(jsonParam);
			logger.info(loggerInfo+"校验参数合法性:"+validMsg);
			if(validMsg!=null){
				String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.CHECK_CODE, "", validMsg);
				// 处理返回结果
				CommonUtil.responseJsonNotEncrypt(result, response);
				return;
			}
			
			String resultMsg=kcodeChannelService.importKcodeInfo(loggerInfo, jsonParam);
			logger.info(resultMsg+"k码数据导入结果:"+resultMsg);
			if(resultMsg!=null){
				String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "", resultMsg);
				// 处理返回结果
				CommonUtil.responseJsonNotEncrypt(result, response);
				return;
			}
			
		} catch (Exception e) {
			logger.error(loggerInfo+"k码数据导入异常",e);
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "","k码数据导入异常！");
			// 处理返回结果
			CommonUtil.responseJsonNotEncrypt(result, response);
			return;
		}
		
		String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.SUCCESS_CODE, "", "导入成功！");
		logger.info(loggerInfo+"end");
		CommonUtil.responseJsonNotEncrypt(result, response);
	
    }

	private String validParams(JSONObject jsonParam) {
		if(jsonParam==null||jsonParam.isEmpty()){
			return "请求参数不能为空";
		}
		
		if(!jsonParam.containsKey("cardNo")||StringUtils.isBlank(jsonParam.getString("cardNo"))){
			return "卡号不能为空";
		}
		
		if(jsonParam.get("cardNo").toString().length()!=10){
			return "卡号格式错误";
		}
		
		if(!jsonParam.containsKey("channelId")||StringUtils.isBlank(jsonParam.getString("channelId"))){
			return "渠道id不能为空";
		}
		
		if(!jsonParam.containsKey("channelName")||StringUtils.isBlank(jsonParam.getString("channelName"))){
			return "渠道名称不能为空";
		}
		
		if(!jsonParam.containsKey("channel")||StringUtils.isBlank(jsonParam.getString("channel"))){
			return "请求渠道不能为空";
		}
		
		if(!jsonParam.get("channel").equals("PHICOMM")){
			return "请求渠道不正确";
		}
		
		return null;
	}
	
	/**
	 * 老版本判断,小于3.2.0版本或版本号为空弹更新提示（安卓端）
	 * @param logInfo
	 * @param reqMap
	 * @return
	 */
	private boolean isOldVersion(String logInfo,HashMap<String, Object> reqMap) {
		logger.info(logInfo+" 版本判断start");
		String androidVersion=nullToBlank(reqMap.get("versionId")).trim();//安卓版本号
		String iosVersion=nullToBlank(reqMap.get("version")).trim();//ios版本号
		String channel = nullToBlank(reqMap.get("channel")).trim();//渠道
		
		logger.info(logInfo +"{channel:"+channel+",androidVersion:" + androidVersion+",iosVersion:"+iosVersion+"}");
		
		if(StringUtils.isNotBlank(channel)){
			if(channel.equalsIgnoreCase("LBANDROID")){
				if(StringUtils.isNotBlank(androidVersion)){
					if(Integer.valueOf(androidVersion.replace(".",""))<320){
						logger.info(logInfo+" app版本低于3.2.0");
						return true;
					}
				}else{
					logger.info(logInfo+" app版本低于老版本(无版本号)");
					return true;
				}
			}
		}
		logger.info(logInfo+" 版本判断end");
		return false;
	}

}
